在 Linux 上使用 Nginx 裝載 ASP.NET CoreHost ASP.NET Core on Linux with Nginx

Sourabh Shirhatti 提供By Sourabh Shirhatti

本指南說明在 Ubuntu 16.04 伺服器上設定生產環境就緒的 ASP.NET Core 環境。This guide explains setting up a production-ready ASP.NET Core environment on an Ubuntu 16.04 server. 這些指示可能使用較新版本的 Ubuntu,但未經測試。These instructions likely work with newer versions of Ubuntu, but the instructions haven't been tested with newer versions.

如需有關 ASP.NET Core 支援之其他 Linux 發行版本的資訊,請參閱 Linux 上 .NET Core 的必要條件For information on other Linux distributions supported by ASP.NET Core, see Prerequisites for .NET Core on Linux.

注意

針對 Ubuntu 14.04, supervisord 建議使用此解決方案來監視 Kestrel 流程。For Ubuntu 14.04, supervisord is recommended as a solution for monitoring the Kestrel process. systemd 在 Ubuntu 14.04 上無法使用。systemd isn't available on Ubuntu 14.04. 如需 Ubuntu 14.04 指示,請參閱本主題前一版本For Ubuntu 14.04 instructions, see the previous version of this topic.

本指南:This guide:

  • 將現有的 ASP.NET Core 應用程式放在反向 Proxy 伺服器後方。Places an existing ASP.NET Core app behind a reverse proxy server.
  • 設定反向 Proxy 伺服器以將要求轉送至 Kestrel 網頁伺服器。Sets up the reverse proxy server to forward requests to the Kestrel web server.
  • 確保 Web 應用程式在啟動時以精靈的形式執行。Ensures the web app runs on startup as a daemon.
  • 設定程序管理工具以協助重新啟動 Web 應用程式。Configures a process management tool to help restart the web app.

必要條件Prerequisites

  • 以 sudo 權限使用標準使用者帳戶存取 Ubuntu 16.04 伺服器。Access to an Ubuntu 16.04 server with a standard user account with sudo privilege.
  • 安裝在伺服器上的最新非預覽版 .net 運行 時間。The latest non-preview .NET runtime installed on the server.
  • 現有的 ASP.NET Core 應用程式。An existing ASP.NET Core app.

在升級共用架構之後的任何時間點,重新開機伺服器所裝載的 ASP.NET Core 應用程式。At any point in the future after upgrading the shared framework, restart the ASP.NET Core apps hosted by the server.

跨應用程式發佈與複製Publish and copy over the app

架構相依部署設定應用程式。Configure the app for a framework-dependent deployment.

如果應用程式在本機執行且未設定為進行安全連線 (HTTPS),請採用下列任一方法:If the app is run locally and isn't configured to make secure connections (HTTPS), adopt either of the following approaches:

  • 設定應用程式以處理安全的本機連線。Configure the app to handle secure local connections. 如需詳細資訊,請參閱 HTTPS 組態一節。For more information, see the HTTPS configuration section.
  • https://localhost:5001從檔案的屬性中移除 ((如果有) 的話) applicationUrl Properties/launchSettings.jsonRemove https://localhost:5001 (if present) from the applicationUrl property in the Properties/launchSettings.json file.

從開發環境執行 dotnet publish ,以將應用程式封裝到目錄中 (例如, bin/Release/{TARGET FRAMEWORK MONIKER}/publish 其中預留位置 {TARGET FRAMEWORK MONIKER} 是可在伺服器上執行的目標 Framework 標記/TFM) :Run dotnet publish from the development environment to package an app into a directory (for example, bin/Release/{TARGET FRAMEWORK MONIKER}/publish, where the placeholder {TARGET FRAMEWORK MONIKER} is the Target Framework Moniker/TFM) that can run on the server:

dotnet publish --configuration Release

如果您不想在伺服器上維護 .NET Core 執行階段,應用程式也可以發佈為獨立式部署The app can also be published as a self-contained deployment if you prefer not to maintain the .NET Core runtime on the server.

使用整合至組織工作流程的工具,將 ASP.NET Core 應用程式複製到伺服器 (例如, SCP SFTP) 。Copy the ASP.NET Core app to the server using a tool that integrates into the organization's workflow (for example, SCP, SFTP). 通常會在目錄底下尋找 web 應用程式 var (例如 var/www/helloapp) 。It's common to locate web apps under the var directory (for example, var/www/helloapp).

注意

在生產環境部署案例中,持續整合工作流程會執行發佈應用程式並將資產複製到伺服器的工作。Under a production deployment scenario, a continuous integration workflow does the work of publishing the app and copying the assets to the server.

測試應用程式:Test the app:

  1. 從命令列執行應用程式:dotnet <app_assembly>.dllFrom the command line, run the app: dotnet <app_assembly>.dll.
  2. 在瀏覽器中,巡覽至 http://<serveraddress>:<port> 以確認應用程式可在 Linux 本機上正常運作。In a browser, navigate to http://<serveraddress>:<port> to verify the app works on Linux locally.

設定反向 Proxy 伺服器Configure a reverse proxy server

反向 Proxy 是為動態 Web 應用程式提供服務的常見設定。A reverse proxy is a common setup for serving dynamic web apps. 反向 Proxy 會終止 HTTP 要求,並將它轉送至 ASP.NET Core 應用程式。A reverse proxy terminates the HTTP request and forwards it to the ASP.NET Core app.

使用反向 Proxy 伺服器Use a reverse proxy server

Kestrel 非常適用於從 ASP.NET Core 提供動態內容。Kestrel is great for serving dynamic content from ASP.NET Core. 不過,Web 服務功能不像 IIS、Apache 或 Nginx 這類伺服器那樣豐富。However, the web serving capabilities aren't as feature rich as servers such as IIS, Apache, or Nginx. 反向 Proxy 伺服器可以讓 HTTP 伺服器卸下提供靜態內容、快取要求、壓縮要求及終止 HTTPS 等工作的負擔。A reverse proxy server can offload work such as serving static content, caching requests, compressing requests, and HTTPS termination from the HTTP server. 反向 Proxy 伺服器可能位在專用電腦上,或可能與 HTTP 伺服器一起部署。A reverse proxy server may reside on a dedicated machine or may be deployed alongside an HTTP server.

為達到本指南的目的,使用 Nginx 的單一執行個體。For the purposes of this guide, a single instance of Nginx is used. 它會在相同的伺服器上和 HTTP 伺服器一起執行。It runs on the same server, alongside the HTTP server. 您可以根據需求,選擇不同的設定。Based on requirements, a different setup may be chosen.

因為反向 proxy 會轉送要求,所以請使用封裝中 轉送的標頭中介軟體 Microsoft.AspNetCore.HttpOverridesBecause requests are forwarded by reverse proxy, use the Forwarded Headers Middleware from the Microsoft.AspNetCore.HttpOverrides package. 此中介軟體會使用 X-Forwarded-Proto 標頭來更新 Request.Scheme,以便讓重新導向 URI 及其他安全性原則正確運作。The middleware updates the Request.Scheme, using the X-Forwarded-Proto header, so that redirect URIs and other security policies work correctly.

轉送的標頭中介軟體應該在其他中介軟體之前執行。Forwarded Headers Middleware should run before other middleware. 這種排序可確保依賴轉送標頭資訊的中介軟體可以耗用用於處理的標頭值。This ordering ensures that the middleware relying on forwarded headers information can consume the header values for processing. 若要在診斷和錯誤處理中介軟體之後執行轉送的標頭中介軟體,請參閱 轉送標頭中介軟體順序To run Forwarded Headers Middleware after diagnostics and error handling middleware, see Forwarded Headers Middleware order.

UseForwardedHeadersStartup.Configure 呼叫其他中介軟體之前,先在頂端叫用方法。Invoke the UseForwardedHeaders method at the top of Startup.Configure before calling other middleware. 請設定中介軟體來轉送 X-Forwarded-ForX-Forwarded-Proto 標頭:Configure the middleware to forward the X-Forwarded-For and X-Forwarded-Proto headers:

using Microsoft.AspNetCore.HttpOverrides;

...

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});

app.UseAuthentication();

如果未將任何 ForwardedHeadersOptions 指定給中介軟體,則要轉送的預設標頭會是 NoneIf no ForwardedHeadersOptions are specified to the middleware, the default headers to forward are None.

預設會信任在回送位址上執行的 proxy (127.0.0.0/8[::1]) (包括標準 localhost 位址 (127.0.0.1) )。Proxies running on loopback addresses (127.0.0.0/8, [::1]), including the standard localhost address (127.0.0.1), are trusted by default. 如果組織內有其他受信任的 Proxy 或網路處理網際網路與網頁伺服器之間的要求,請使用 ForwardedHeadersOptions,將其新增至 KnownProxiesKnownNetworks 清單。If other trusted proxies or networks within the organization handle requests between the Internet and the web server, add them to the list of KnownProxies or KnownNetworks with ForwardedHeadersOptions. 下列範例會將 IP 位址 10.0.0.100 的受信任 Proxy 伺服器新增至 Startup.ConfigureServices 中「轉送的標頭中介軟體」的 KnownProxiesThe following example adds a trusted proxy server at IP address 10.0.0.100 to the Forwarded Headers Middleware KnownProxies in Startup.ConfigureServices:

using System.Net;

...

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.KnownProxies.Add(IPAddress.Parse("10.0.0.100"));
});

如需詳細資訊,請參閱設定 ASP.NET Core 以與 Proxy 伺服器和負載平衡器搭配運作For more information, see 設定 ASP.NET Core 以與 Proxy 伺服器和負載平衡器搭配運作.

安裝 NginxInstall Nginx

使用 apt-get 來安裝 Nginx。Use apt-get to install Nginx. 安裝程式會建立在 systemd 系統啟動時執行 Nginx 做為 daemon 的 init 腳本。The installer creates a systemd init script that runs Nginx as daemon on system startup. 請遵循 Nginx:Official Debian/Ubuntu packages (Nginx:官方 Debian/Ubuntu 套件) 中適用於 Ubuntu 的安裝指示。Follow the installation instructions for Ubuntu at Nginx: Official Debian/Ubuntu packages.

注意

如果需要選用的 Nginx 模組,可能要從來源建置 Nginx。If optional Nginx modules are required, building Nginx from source might be required.

因為 Nginx 是第一次安裝,請透過執行明確啟動它:Since Nginx was installed for the first time, explicitly start it by running:

sudo service nginx start

確認瀏覽器會顯示 Nginx 的預設登陸頁面。Verify a browser displays the default landing page for Nginx. 登陸頁面位於 http://<server_IP_address>/index.nginx-debian.htmlThe landing page is reachable at http://<server_IP_address>/index.nginx-debian.html.

設定 NginxConfigure Nginx

若要將 Nginx 設定為反向 proxy,以將 HTTP 要求轉送至 ASP.NET Core 應用程式,請修改 /etc/nginx/sites-available/defaultTo configure Nginx as a reverse proxy to forward HTTP requests to your ASP.NET Core app, modify /etc/nginx/sites-available/default. 在文字編輯器中開啟它,並將內容取代為下列程式碼片段:Open it in a text editor, and replace the contents with the following snippet:

server {
    listen        80;
    server_name   example.com *.example.com;
    location / {
        proxy_pass         http://127.0.0.1:5000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

如果應用程式是 SignalR 或 Blazor Server 應用程式,請 ASP.NET Core SignalR 生產裝載和調整規模 分別參閱和, 裝載和部署 ASP.NET Core Blazor Server 以取得詳細資訊。If the app is a SignalR or Blazor Server app, see ASP.NET Core SignalR 生產裝載和調整規模 and 裝載和部署 ASP.NET Core Blazor Server respectively for more information.

當沒有任何與 server_name 相符的項目時,Nginx 會使用預設伺服器。When no server_name matches, Nginx uses the default server. 如果未定義任何預設伺服器,則設定檔中的第一個伺服器就是預設伺服器。If no default server is defined, the first server in the configuration file is the default server. 最佳做法是在您的設定檔中新增會傳回狀態碼444的特定預設伺服器。As a best practice, add a specific default server that returns a status code of 444 in your configuration file. 預設伺服器設定範例如下:A default server configuration example is:

server {
    listen   80 default_server;
    # listen [::]:80 default_server deferred;
    return   444;
}

使用上述設定檔和預設伺服器時,Nginx 會在連接埠 80 接受主機標頭為 example.com*.example.com 的公用流量。With the preceding configuration file and default server, Nginx accepts public traffic on port 80 with host header example.com or *.example.com. 不符合這些主機的要求將不會轉送至 Kestrel。Requests not matching these hosts won't get forwarded to Kestrel. Nginx 會將相符的要求轉送至位於 http://127.0.0.1:5000 的 Kestrel。Nginx forwards the matching requests to Kestrel at http://127.0.0.1:5000. 如需詳細資訊,請參閱 nginx 處理要求的方式For more information, see How nginx processes a request. 若要變更 Kestrel 的 IP/連接埠,請參閱 Kestrel:端點組態To change Kestrel's IP/port, see Kestrel: Endpoint configuration.

使用上述設定檔和預設伺服器時,Nginx 會在連接埠 80 接受主機標頭為 example.com*.example.com 的公用流量。With the preceding configuration file and default server, Nginx accepts public traffic on port 80 with host header example.com or *.example.com. 不符合這些主機的要求將不會轉送至 Kestrel。Requests not matching these hosts won't get forwarded to Kestrel. Nginx 會將相符的要求轉送至位於 http://127.0.0.1:5000 的 Kestrel。Nginx forwards the matching requests to Kestrel at http://127.0.0.1:5000. 如需詳細資訊,請參閱 nginx 處理要求的方式For more information, see How nginx processes a request. 若要變更 Kestrel 的 IP/連接埠,請參閱 Kestrel:端點組態To change Kestrel's IP/port, see Kestrel: Endpoint configuration.

警告

如果無法指定適當的 server_name 指示詞,就會讓應用程式暴露在安全性弱點的風險下。Failure to specify a proper server_name directive exposes your app to security vulnerabilities. 若您擁有整個父網域 (相對於易受攻擊的 *.com) 的控制權,子網域萬用字元繫結 (例如 *.example.com) 就沒有此安全性風險。Subdomain wildcard binding (for example, *.example.com) doesn't pose this security risk if you control the entire parent domain (as opposed to *.com, which is vulnerable). 如需詳細資訊,請參閱 rfc7230 章節-5.4For more information, see rfc7230 section-5.4.

建立 Nginx 設定之後,請執行 sudo nginx -t 來確認設定檔的語法。Once the Nginx configuration is established, run sudo nginx -t to verify the syntax of the configuration files. 如果設定檔測試成功,請執行 sudo nginx -s reload 來強制 Nginx 套用這些變更。If the configuration file test is successful, force Nginx to pick up the changes by running sudo nginx -s reload.

直接在伺服器上執行應用程式:To directly run the app on the server:

  1. 巡覽至應用程式目錄。Navigate to the app's directory.
  2. 執行應用程式:dotnet <app_assembly.dll>,其中 app_assembly.dll 是應用程式的組件檔名稱。Run the app: dotnet <app_assembly.dll>, where app_assembly.dll is the assembly file name of the app.

如果應用程式在伺服器上執行,但無法透過網際網路回應,請檢查伺服器的防火牆,並確認埠80已開啟。If the app runs on the server but fails to respond over the Internet, check the server's firewall and confirm port 80 is open. 如果使用的是 Azure Ubuntu VM,請新增啓用輸入連接埠 80 流量的網路安全性群組 (NSG) 規則。If using an Azure Ubuntu VM, add a Network Security Group (NSG) rule that enables inbound port 80 traffic. 沒有必要啟用輸出連接埠 80 規則,因為啓用輸入規則時會自動授與輸出流量。There's no need to enable an outbound port 80 rule, as the outbound traffic is automatically granted when the inbound rule is enabled.

完成測試應用程式時,請在命令提示字元下使用Ctrl +關閉應用程式 + When done testing the app, shut down the app with Ctrl + C at the command prompt.

監視應用程式Monitor the app

伺服器會設定為將對執行的要求轉寄至在 http://<serveraddress>:80 Kestrel 上執行的 ASP.NET Core 應用程式 http://127.0.0.1:5000The server is set up to forward requests made to http://<serveraddress>:80 on to the ASP.NET Core app running on Kestrel at http://127.0.0.1:5000. 不過,並未設定 Nginx 來管理 Kestrel 處理序。However, Nginx isn't set up to manage the Kestrel process. systemd 可以用來建立服務檔案,以啟動並監視基礎 web 應用程式。systemd can be used to create a service file to start and monitor the underlying web app. systemd 是 init 系統,提供許多強大的功能來啟動、停止及管理進程。systemd is an init system that provides many powerful features for starting, stopping, and managing processes.

建立服務檔Create the service file

建立服務定義檔:Create the service definition file:

sudo nano /etc/systemd/system/kestrel-helloapp.service

下列範例是應用程式的服務檔:The following example is a service file for the app:

[Unit]
Description=Example .NET Web API App running on Ubuntu

[Service]
WorkingDirectory=/var/www/helloapp
ExecStart=/usr/bin/dotnet /var/www/helloapp/helloapp.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-example
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target

在上述範例中,管理服務的使用者是由選項所指定 UserIn the preceding example, the user that manages the service is specified by the User option. 使用者 (www-data) 必須存在,且擁有應用程式檔案的適當擁有權。The user (www-data) must exist and have proper ownership of the app's files.

使用 TimeoutStopSec 可設定應用程式收到初始中斷訊號之後等待關閉的時間。Use TimeoutStopSec to configure the duration of time to wait for the app to shut down after it receives the initial interrupt signal. 如果應用程式在此期間後未關閉,則會發出 SIGKILL 來終止應用程式。If the app doesn't shut down in this period, SIGKILL is issued to terminate the app. 提供不具單位的秒值 (例如 150)、時間範圍值 (例如 2min 30s) 或 infinity (表示停用逾時)。Provide the value as unitless seconds (for example, 150), a time span value (for example, 2min 30s), or infinity to disable the timeout. TimeoutStopSec 預設為 DefaultTimeoutStopSec manager 設定檔中的值 systemd-system.conf , (、 system.conf.dsystemd-user.conf user.conf.d) 。TimeoutStopSec defaults to the value of DefaultTimeoutStopSec in the manager configuration file (systemd-system.conf, system.conf.d, systemd-user.conf, user.conf.d). 大多數發行版本的預設逾時為 90 秒。The default timeout for most distributions is 90 seconds.

# The default value is 90 seconds for most distributions.
TimeoutStopSec=90

Linux 的檔案系統會區分大小寫。Linux has a case-sensitive file system. 將設定 ASPNETCORE_ENVIRONMENTProduction 會導致搜尋設定檔 appsettings.Production.json ,而不是 appsettings.production.jsonSetting ASPNETCORE_ENVIRONMENT to Production results in searching for the configuration file appsettings.Production.json, not appsettings.production.json.

有些值 (例如 SQL 連接字串) 必須以逸出方式處理,設定提供者才能讀取環境變數。Some values (for example, SQL connection strings) must be escaped for the configuration providers to read the environment variables. 請使用下列命令來產生要在設定檔中使用並已適當逸出的值:Use the following command to generate a properly escaped value for use in the configuration file:

systemd-escape "<value-to-escape>"

環境變數名稱不支援冒號 (:) 分隔符號。Colon (:) separators aren't supported in environment variable names. 請使用雙底線 (__) 來取代冒號。Use a double underscore (__) in place of a colon. 環境變數組態提供者會在將環境變數讀入組態時,將雙底線轉換為冒號。The Environment Variables configuration provider converts double-underscores into colons when environment variables are read into configuration. 在下列範例中,連接字串索引鍵 ConnectionStrings:DefaultConnection 會設定為服務定義檔中的 ConnectionStrings__DefaultConnectionIn the following example, the connection string key ConnectionStrings:DefaultConnection is set into the service definition file as ConnectionStrings__DefaultConnection:

環境變數名稱不支援冒號 (:) 分隔符號。Colon (:) separators aren't supported in environment variable names. 請使用雙底線 (__) 來取代冒號。Use a double underscore (__) in place of a colon. 環境變數組態提供者會在將環境變數讀入組態時,將雙底線轉換為冒號。The Environment Variables configuration provider converts double-underscores into colons when environment variables are read into configuration. 在下列範例中,連接字串索引鍵 ConnectionStrings:DefaultConnection 會設定為服務定義檔中的 ConnectionStrings__DefaultConnectionIn the following example, the connection string key ConnectionStrings:DefaultConnection is set into the service definition file as ConnectionStrings__DefaultConnection:

Environment=ConnectionStrings__DefaultConnection={Connection String}

儲存檔案並啟用服務。Save the file and enable the service.

sudo systemctl enable kestrel-helloapp.service

啟動服務並確認它正在執行。Start the service and verify that it's running.

sudo systemctl start kestrel-helloapp.service
sudo systemctl status kestrel-helloapp.service

◝ kestrel-helloapp.service - Example .NET Web API App running on Ubuntu
    Loaded: loaded (/etc/systemd/system/kestrel-helloapp.service; enabled)
    Active: active (running) since Thu 2016-10-18 04:09:35 NZDT; 35s ago
Main PID: 9021 (dotnet)
    CGroup: /system.slice/kestrel-helloapp.service
            └─9021 /usr/local/bin/dotnet /var/www/helloapp/helloapp.dll

透過設定反向 proxy 並透過管理 Kestrel systemd ,web 應用程式就會完整設定,並可在本機電腦上的瀏覽器中存取 http://localhostWith the reverse proxy configured and Kestrel managed through systemd, the web app is fully configured and can be accessed from a browser on the local machine at http://localhost. 此外,也可以從遠端電腦存取它,除非遭到任何防火牆封鎖。It's also accessible from a remote machine, barring any firewall that might be blocking. 檢查回應標頭時,Server 標頭會顯示是由 Kestrel 為 ASP.NET Core 應用程式提供服務。Inspecting the response headers, the Server header shows the ASP.NET Core app being served by Kestrel.

HTTP/1.1 200 OK
Date: Tue, 11 Oct 2016 16:22:23 GMT
Server: Kestrel
Keep-Alive: timeout=5, max=98
Connection: Keep-Alive
Transfer-Encoding: chunked

檢視記錄View logs

由於是使用 systemd 來管理使用 Kestrel 的 Web 應用程式,因此會將所有事件和處理序都記錄在集中式日誌中。Since the web app using Kestrel is managed using systemd, all events and processes are logged to a centralized journal. 不過,此日誌包含 systemd 管理的所有服務和處理程序的所有項目。However, this journal includes all entries for all services and processes managed by systemd. 若要檢視 kestrel-helloapp.service 的特定項目,請使用下列命令:To view the kestrel-helloapp.service-specific items, use the following command:

sudo journalctl -fu kestrel-helloapp.service

如需進一步的篩選,時間選項(例如 --since today--until 1 hour ago 或)的組合可以減少傳回的專案數。For further filtering, time options such as --since today, --until 1 hour ago, or a combination of these can reduce the number of entries returned.

sudo journalctl -fu kestrel-helloapp.service --since "2016-10-18" --until "2016-10-18 04:00"

資料保護Data protection

ASP.NET Core 的資料保護堆疊是由數個 ASP.NET Core中介軟體所使用,包括驗證中介軟體 (例如, cookie 中介軟體) 和跨網站偽造要求 (CSRF) 保護。The ASP.NET Core Data Protection stack is used by several ASP.NET Core middlewares, including authentication middleware (for example, cookie middleware) and cross-site request forgery (CSRF) protections. 即使資料保護 API 並非由使用者程式碼呼叫,仍應設定資料保護,以建立持續密碼編譯金鑰存放區Even if Data Protection APIs aren't called by user code, data protection should be configured to create a persistent cryptographic key store. 如不設定資料保護,金鑰會保留在記憶體中,並於應用程式重新啟動時捨棄。If data protection isn't configured, the keys are held in memory and discarded when the app restarts.

如果 Keyring 儲存在記憶體中,則當應用程式重新啟動時:If the key ring is stored in memory when the app restarts:

  • 所有 cookie 的驗證權杖都會失效。All cookie-based authentication tokens are invalidated.
  • 當使用者提出下一個要求時,需要再次登入。Users are required to sign in again on their next request.
  • 所有以 Keyring 保護的資料都無法再解密。Any data protected with the key ring can no longer be decrypted. 這可能包括 CSRF 權杖ASP.NET Core MVC TempData cookie sThis may include CSRF tokens and ASP.NET Core MVC TempData cookies.

若要設定資料保護來保存及加密金鑰環,請參閱:To configure data protection to persist and encrypt the key ring, see:

要求標頭欄位太長Long request header fields

Proxy 伺服器預設設定通常會將要求標頭欄位限制為 4 K 或 8 K (視平臺而定)。Proxy server default settings typically limit request header fields to 4 K or 8 K depending on the platform. 應用程式可能需要比預設 (更長的欄位,例如使用 Azure Active Directory) 的應用程式。An app may require fields longer than the default (for example, apps that use Azure Active Directory). 如果需要較長的欄位,proxy 伺服器的預設設定需要進行調整。If longer fields are required, the proxy server's default settings require adjustment. 要套用的值取決於案例。The values to apply depend on the scenario. 如需詳細資訊,請參閱您的伺服器文件。For more information, see your server's documentation.

警告

除非必要,否則請勿增加 Proxy 緩衝區的預設值。Don't increase the default values of proxy buffers unless necessary. 增加這些值會提高緩衝區溢位及惡意使用者發動拒絕服務 (DoS) 攻擊的風險。Increasing these values increases the risk of buffer overrun (overflow) and Denial of Service (DoS) attacks by malicious users.

保護應用程式Secure the app

啟用 AppArmorEnable AppArmor

Linux 安全性模組 (LSM) 是 Linux 2.6 之後 Linux 核心所包含的一個架構。Linux Security Modules (LSM) is a framework that's part of the Linux kernel since Linux 2.6. LSM 支援不同的安全性模組實作。LSM supports different implementations of security modules. AppArmor 是一個 LSM,可執行強制存取控制系統,讓您將程式將到一組有限的資源。AppArmor is an LSM that implements a Mandatory Access Control system, which allows confining the program to a limited set of resources. 確定已啟用並正確設定 AppArmor。Ensure AppArmor is enabled and properly configured.

設定防火牆Configure the firewall

關閉所有未使用的外部埠。Close off all external ports that aren't in use. 簡單的防火牆 (ufw) 提供可設定防火牆的 CLI 來提供前端 iptablesUncomplicated firewall (ufw) provides a front end for iptables by providing a CLI for configuring the firewall.

警告

如未正確設定,防火牆會禁止存取整個系統。A firewall will prevent access to the whole system if not configured correctly. 未指定正確的 SSH 連接埠,將會導致您無法存取系統 (若您使用 SSH 連線至該連接埠)。Failure to specify the correct SSH port will effectively lock you out of the system if you are using SSH to connect to it. 預設連接埠為 22。The default port is 22. 如需詳細資訊,請參閱 ufw 簡介手冊For more information, see the introduction to ufw and the manual.

安裝 ufw 並將其設定為允許任何所需連接埠上的流量。Install ufw and configure it to allow traffic on any ports needed.

sudo apt-get install ufw

sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

sudo ufw enable

保護 NginxSecure Nginx

變更 Nginx 回應名稱Change the Nginx response name

編輯 src/http/ngx_http_header_filter_module.cEdit src/http/ngx_http_header_filter_module.c:

static char ngx_http_server_string[] = "Server: Web Server" CRLF;
static char ngx_http_server_full_string[] = "Server: Web Server" CRLF;

設定選項Configure options

設定伺服器的其他所需模組。Configure the server with additional required modules. 請考慮使用 ModSecurity 等 Web 應用程式防火牆來強化應用程式。Consider using a web app firewall, such as ModSecurity, to harden the app.

HTTPS 設定HTTPS configuration

設定應用程式以進行安全的本機連線 (HTTPS)Configure the app for secure (HTTPS) local connections

Dotnet run命令使用應用程式的 Properties/launchSettings.json 檔案,其會將應用程式設定為在屬性提供的 url 上接聽 applicationUrlThe dotnet run command uses the app's Properties/launchSettings.json file, which configures the app to listen on the URLs provided by the applicationUrl property. 例如: https://localhost:5001;http://localhost:5000For example, https://localhost:5001;http://localhost:5000.

使用下列其中一種方法,將應用程式設定為在 dotnet run 命令或開發環境的開發環境中使用憑證 (F5Ctrl + F5 Visual Studio Code) :Configure the app to use a certificate in development for the dotnet run command or development environment (F5 or Ctrl+F5 in Visual Studio Code) using one of the following approaches:

設定反向 Prooxy 以進行安全的用戶端連線 (HTTPS)Configure the reverse proxy for secure (HTTPS) client connections

警告

本節中的安全性設定是一般設定,可作為進一步自訂的起點。The security configuration in this section is a general configuration to be used as a starting point for further customization. 我們無法提供協力廠商工具、伺服器和作業系統的支援。We're unable to provide support for third-party tooling, servers, and operating systems. 使用本節中的設定,以您自己的風險。Use the configuration in this section at your own risk. 如需詳細資訊,請存取下列資源:For more information, access the following resources:

  • 藉由指定由受信任的憑證授權單位單位所簽發的有效憑證 (CA) ,將伺服器設定為接聽埠443上的 HTTPS 流量。Configure the server to listen to HTTPS traffic on port 443 by specifying a valid certificate issued by a trusted Certificate Authority (CA).

  • 採用以下 /etc/nginx/nginx.conf 檔案所述的一些做法來強化安全性。Harden the security by employing some of the practices depicted in the following /etc/nginx/nginx.conf file.

  • 下列範例不會將伺服器設定為重新導向不安全的要求。The following example doesn't configure the server to redirect insecure requests. 建議使用 HTTPS 重新導向中介軟體。We recommend using HTTPS Redirection Middleware. 如需詳細資訊,請參閱在 ASP.NET Core 中強制使用 HTTPSFor more information, see 在 ASP.NET Core 中強制使用 HTTPS.

    注意

    針對伺服器設定處理安全重新導向而非 HTTPS 重新導向中介軟體的開發環境,我們建議使用暫時性重新導向 (302) ,而不是永久重新導向 (301) 。For development environments where the server configuration handles secure redirection instead of HTTPS Redirection Middleware, we recommend using temporary redirects (302) rather than permanent redirects (301). 連結快取可能會在開發環境中造成不穩定的行為。Link caching can cause unstable behavior in development environments.

  • 新增 Strict-Transport-Security (HSTS) 標頭可確保用戶端提出的所有後續要求都是透過 HTTPS。Adding a Strict-Transport-Security (HSTS) header ensures all subsequent requests made by the client are over HTTPS. 如需設定 Strict-Transport-Security 標頭的指引,請參閱 在 ASP.NET Core 中強制使用 HTTPSFor guidance on setting the Strict-Transport-Security header, see 在 ASP.NET Core 中強制使用 HTTPS.

  • 如果未來將停用 HTTPS,請使用下列其中一種方法:If HTTPS will be disabled in the future, use one of the following approaches:

    • 請勿新增 HSTS 標頭。Don't add the HSTS header.
    • 選擇簡短 max-age 值。Choose a short max-age value.

新增 /etc/nginx/Proxy.conf 組態檔:Add the /etc/nginx/proxy.conf configuration file:

proxy_redirect          off;
proxy_set_header        Host $host;
proxy_set_header        X-Real-IP $remote_addr;
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header        X-Forwarded-Proto $scheme;
client_max_body_size    10m;
client_body_buffer_size 128k;
proxy_connect_timeout   90;
proxy_send_timeout      90;
proxy_read_timeout      90;
proxy_buffers           32 4k;

/etc/nginx/nginx.conf 設定檔的內容 取代 為下列檔案。Replace the contents of the /etc/nginx/nginx.conf configuration file with the following file. 此範例在一個組態檔中同時包含 httpserver 區段。The example contains both http and server sections in one configuration file.

http {
    include        /etc/nginx/proxy.conf;
    limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s;
    server_tokens  off;

    sendfile on;
    # Adjust keepalive_timeout to the lowest possible value that makes sense 
    # for your use case.
    keepalive_timeout   29;
    client_body_timeout 10; client_header_timeout 10; send_timeout 10;

    upstream helloapp{
        server 127.0.0.1:5000;
    }

    server {
        listen                    443 ssl http2;
        listen                    [::]:443 ssl http2;
        server_name               example.com *.example.com;
        ssl_certificate           /etc/ssl/certs/testCert.crt;
        ssl_certificate_key       /etc/ssl/certs/testCert.key;
        ssl_session_timeout       1d;
        ssl_protocols             TLSv1.2 TLSv1.3;
        ssl_prefer_server_ciphers off;
        ssl_ciphers               ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
        ssl_session_cache         shared:SSL:10m;
        ssl_session_tickets       off;
        ssl_stapling              off;

        add_header X-Frame-Options DENY;
        add_header X-Content-Type-Options nosniff;

        #Redirects all traffic
        location / {
            proxy_pass http://helloapp;
            limit_req  zone=one burst=10 nodelay;
        }
    }
}

注意

Blazor WebAssembly 應用程式需要較大的 burst 參數值,以容納應用程式所提出的大量要求。Blazor WebAssembly apps require a larger burst parameter value to accommodate the larger number of requests made by an app. 如需詳細資訊,請參閱裝載和部署 ASP.NET Core Blazor WebAssemblyFor more information, see 裝載和部署 ASP.NET Core Blazor WebAssembly.

注意

上述範例會停用 (OCSP) 裝訂的線上憑證狀態通訊協定。The preceding example disables Online Certificate Status Protocol (OCSP) Stapling. 若已啟用,請確認憑證支援此功能。If enabled, confirm that the certificate supports the feature. 如需有關啟用 OCSP 的詳細資訊和指引,請參閱 模組 ngx_HTTP_ssl_module (Nginx 檔) 文章中的下列屬性:For more information and guidance on enabling OCSP, see the following properties in the Module ngx_http_ssl_module (Nginx documentation) article:

  • ssl_stapling
  • ssl_stapling_file
  • ssl_stapling_responder
  • ssl_stapling_verify

保護 Nginx 免於點閱綁架Secure Nginx from clickjacking

點閱綁架(也稱為「UI 偽裝攻擊」) 是一種惡意攻擊,會誘騙網站訪客點選與其目前所瀏覽頁面不同的頁面上連結或按鈕。Clickjacking, also known as a UI redress attack, is a malicious attack where a website visitor is tricked into clicking a link or button on a different page than they're currently visiting. 請使用 X-FRAME-OPTIONS 來保護網站安全。Use X-FRAME-OPTIONS to secure the site.

減輕點擊劫持攻擊:To mitigate clickjacking attacks:

  1. 編輯 nginx.conf 檔案:Edit the nginx.conf file:

    sudo nano /etc/nginx/nginx.conf
    

    新增行: add_header X-Frame-Options "SAMEORIGIN";Add the line: add_header X-Frame-Options "SAMEORIGIN";

  2. 儲存檔案。Save the file.

  3. 重新啟動 Nginx。Restart Nginx.

MIME 類型探查MIME-type sniffing

此標頭會防止大部分的瀏覽器對遠離宣告內容類型的回應進行 MIME 探查,因為標頭會指示瀏覽器不要覆寫回應內容類型。This header prevents most browsers from MIME-sniffing a response away from the declared content type, as the header instructs the browser not to override the response content type. 使用 nosniff 選項時,如果伺服器顯示的內容是 text/html ,則瀏覽器會將它轉譯為 text/htmlWith the nosniff option, if the server says the content is text/html, the browser renders it as text/html.

  1. 編輯 nginx.conf 檔案:Edit the nginx.conf file:

    sudo nano /etc/nginx/nginx.conf
    

    新增行: add_header X-Content-Type-Options "nosniff";Add the line: add_header X-Content-Type-Options "nosniff";

  2. 儲存檔案。Save the file.

  3. 重新啟動 Nginx。Restart Nginx.

其他 Nginx 建議Additional Nginx suggestions

在伺服器上升級共用架構之後,請重新開機伺服器所裝載的 ASP.NET Core 應用程式。After upgrading the shared framework on the server, restart the ASP.NET Core apps hosted by the server.

其他資源Additional resources