次の方法で共有


Nginx を使用 ASP.NET Core Blazor WebAssembly をホストしてデプロイする

Andrii Annenko

これは、この記事の最新バージョンではありません。 現在のリリースについては、 この記事の .NET 10 バージョンを参照してください。

警告

このバージョンの ASP.NET Core はサポート対象から除外されました。 詳細については、 .NET および .NET Core サポート ポリシーを参照してください。 現在のリリースについては、 この記事の .NET 10 バージョンを参照してください。

この記事では、Blazor WebAssembly を使用して .NET 8、9、または 10 を対象とするをホストおよびデプロイする方法について説明します。

この記事では、ホストに直接、または Nginx と発行されたアプリのファイルを含む Docker コンテナーにアプリをデプロイする方法について説明します。 Docker ホスティング セクションでは、アプリの発行、コンテナー イメージ内の Nginx の Web ルートへの発行済み出力のコピー、クライアント側ルーティング用の Nginx の構成、一般的な運用設定の適用について説明します。

最小 Nginx 構成

次の nginx.conf ファイルは、ディスク上に対応するファイルが見つからない場合に常に index.html ファイルを送信するように Nginx を構成する方法を示す最小 Nginx 構成例です。 また、 types ブロックを定義して適切な MIME の種類を提供するように Nginx に指示します (または、 mime.types ファイルを含めます)。

events { }
http {
    types {
        text/html                    html;
        text/css                     css;
        application/javascript       js mjs;
        application/json             json;
        application/manifest+json    webmanifest;

        application/wasm             wasm;

        application/octet-stream     dll pdb webcil;
    }

    server {
        listen 80;

        location / {
            root /usr/share/nginx/html;
            try_files $uri $uri/ /index.html =404;
        }
    }
}

Nginx 構成の完了

次の nginx.conf 例は、最小限の構成に基づいています。 キャッシュ、圧縮、レート制限、およびセキュリティ ヘッダーのオプション設定が含まれています。 コメントを確認し、アプリの要件に基づいて設定を削除または調整します。

events { }
http {
    # Security hardening: Don't reveal the Nginx version in responses.
    server_tokens off;

    # Optional: Rate limiting to prevent a single client from sending too 
    # many requests.
    # Blazor WebAssembly apps can generate many requests during startup.
    limit_req_zone $binary_remote_addr zone=one:10m rate=60r/s;

    # Optional: Cache-Control policy by URI.
    # - index.html and service-worker.js: avoid caching so app updates are picked up.
    # - /_framework/*: fingerprinted assets can be cached long-term.
    map $uri $cache_control {
        default             "max-age=3600";
        /index.html         "no-cache";
        /service-worker.js  "no-cache";

        # IMPORTANT: .NET 8/9 Blazor WASM apps do not fingerprint these files
        # Uncomment if the Blazor WASM app targets .NET 8/9, remove for .NET 10
        # /_framework/blazor.boot.json        "no-cache";
        # /_framework/blazor.webassembly.js   "max-age=3600";
        # /_framework/dotnet.js               "max-age=3600";

        ~^/_framework/      "public, max-age=31536000, immutable";
        ~\.woff2?$          "public, max-age=31536000, immutable";
    }

    # MIME types for Blazor WebAssembly assets.
    types {
        text/html                           html htm;
        text/css                            css;
        application/javascript              js mjs;
        application/json                    json;
        application/manifest+json           webmanifest;
        application/wasm                    wasm;
        text/plain                          txt;
        text/xml                            xml;
        application/octet-stream            bin dll exe pdb blat dat webcil;

        # Images
        image/png                           png;
        image/jpeg                          jpg jpeg;
        image/gif                           gif;
        image/webp                          webp;
        image/avif                          avif;
        image/svg+xml                       svg;
        image/x-icon                        ico;

        # Fonts
        font/woff                           woff;
        font/woff2                          woff2;

        # Fallback for other MIME types
        application/octet-stream            *;
    }

    server {
        listen 80;

        location / {
            # Root path for static site content.
            root      /usr/share/nginx/html;

            # SPA/Blazor routing:
            # - Serve a file if it exists.
            # - Otherwise fall back to index.html.
            try_files $uri $uri/ /index.html =404;

            # Optional: Use the rate limit zone defined above.
            limit_req zone=one burst=60 nodelay;

            # Optional: Serve precompressed *.gz files (when present) instead of 
            # compressing on the fly.
            gzip_static on;

            # Optional: Caching policy based on "map $uri $cache_control" above.
            add_header Cache-Control $cache_control always;

            # Optional: Mitigate MIME sniffing.
            add_header X-Content-Type-Options "nosniff" always;
        }
    }
}

ブラウザー開発者ツールまたはネットワーク トラフィック ツールが、要求が 503 - サービス利用不可 状態コードを受信していることを示す場合は、 rate 値と burst 値を増やします。

運用環境での Nginx Web サーバーの構成に関する詳細については、「Creating NGINX Plus and NGINX Configuration Files」 (NGINX Plus と NGINX 構成ファイルの作成) を参照してください。

Docker のデプロイ

次の Dockerfile は、 Blazor WebAssembly アプリを発行し、Nginx イメージからアプリの静的 Web アセットを提供します。

この例では、次のことを前提としています。

  • アプリのプロジェクト ファイルは BlazorSample.csproj という名前で、Docker ビルド コンテキスト ルートにあります。
  • nginx.conf ファイルは、Docker ビルド コンテキスト ルートで使用できます。

たとえば、 Dockerfilenginx.confBlazorSample.csproj はすべて、コードの残りの部分も配置されているのと同じディレクトリ Blazor 配置されます。 この場合、この作業ディレクトリで docker build が起動されます。

# Build stage
# IMPORTANT: change the dotnet/sdk version to the one that your Blazor app targets
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0-noble AS build
WORKDIR /source

RUN apt update \
    && apt install -y python3 \
    && dotnet workload install wasm-tools

COPY . .
RUN dotnet publish BlazorSample.csproj --output /app

# Runtime stage
FROM nginx:latest
COPY --from=build /app/wwwroot/ /usr/share/nginx/html/
COPY nginx.conf /etc/nginx/nginx.conf

イメージをビルドして実行します。

docker build -t blazor-wasm-nginx .
docker run --rm -p {PORT}:80 blazor-wasm-nginx

詳細については、 Nginx Docker ガイドを参照してください。

Linux でのホストされた展開 (Nginx)

ForwardedHeadersOptions を使用して、X-Forwarded-For および X-Forwarded-Proto ヘッダーを転送するようアプリを構成するには、プロキシ サーバーとロード バランサーで動作するように ASP.NET Core を構成する のガイダンスに従ってください。

サブアプリ パスの構成など、アプリのベース パスの設定の詳細については、「 ASP.NET Core Blazor アプリのベース パス」を参照してください。

ASP.NET Core SignalR アプリ」のガイダンスに従って、次のように変更します。

  • プロキシバッファリング()の構成を削除します。この設定はにのみ適用され、アプリのクライアントとサーバー間の通信には関係ないためです。

  • location パスを /hubroute (location /hubroute { ... }) からサブアプリパス /{PATH} (location /{PATH} { ... }) に変更します。ここで、{PATH} プレースホルダーはサブアプリ パスです。

    次の例では、ルート パス / で要求に応答するアプリのサーバーを構成します。

    http {
        server {
            ...
            location / {
                ...
            }
        }
    }
    

    次の例では、/blazor のサブアプリ パスを次のように構成します。

    http {
        server {
            ...
            location /blazor {
                ...
            }
        }
    }
    

その他のリソース