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

作者:Sourabh ShirhattiBy 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. 在 Ubuntu 14.04 上無法使用 systemdsystemd 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

  1. 以 sudo 權限使用標準使用者帳戶存取 Ubuntu 16.04 伺服器。Access to an Ubuntu 16.04 server with a standard user account with sudo privilege.
  2. 在伺服器上安裝 .NET Core 執行階段。Install the .NET Core runtime on the server.
    1. 請前往 .NET Core 的 All Downloads (下載區) 頁面。Visit the .NET Core All Downloads page.
    2. 在 [執行階段] 下的清單中選取最新的非預覽執行階段。Select the latest non-preview runtime from the list under Runtime.
    3. 選取並遵循符合伺服器 Ubuntu 版本的 Ubuntu 指示。Select and follow the instructions for Ubuntu that match the Ubuntu version of the server.
  3. 現有的 ASP.NET Core 應用程式。An existing ASP.NET Core app.

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

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

從開發環境執行 dotnet publish 將應用程式封裝到可在伺服器上執行的目錄 (例如,bin/Release/<target_framework_moniker>/publish):Run dotnet publish from the development environment to package an app into a directory (for example, bin/Release/<target_framework_moniker>/publish) 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.

使用整合至組織工作流程的工具 (SCP、SFTP 等等) 將 ASP.NET Core 應用程式複製到伺服器。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.HttpOverrides 套件的轉送的標頭中介軟體Because 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.

任何依賴配置的元件,例如驗證、連結產生、重新導向和地理位置,都必須在叫用轉送的標頭中介軟體後放置。Any component that depends on the scheme, such as authentication, link generation, redirects, and geolocation, must be placed after invoking the Forwarded Headers Middleware. 轉送的標頭中介軟體是一般規則,應該先於診斷和錯誤處理中介軟體以外的其他中介軟體執行。As a general rule, Forwarded Headers Middleware should run before other middleware except diagnostics and error handling middleware. 這種排序可確保依賴轉送標頭資訊的中介軟體可以耗用用於處理的標頭值。This ordering ensures that the middleware relying on forwarded headers information can consume the header values for processing.

請先在 Startup.Configure 中叫用 UseForwardedHeaders 方法,再呼叫 UseAuthentication 或類似的驗證配置中介軟體。Invoke the UseForwardedHeaders method in Startup.Configure before calling UseAuthentication or similar authentication scheme middleware. 請設定中介軟體來轉送 X-Forwarded-ForX-Forwarded-Proto 標頭:Configure the middleware to forward the X-Forwarded-For and X-Forwarded-Proto headers:

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

app.UseAuthentication();

請先在 Startup.Configure 中叫用 UseForwardedHeaders 方法,再呼叫 UseIdentityUseFacebookAuthentication 或類似的驗證配置中介軟體。Invoke the UseForwardedHeaders method in Startup.Configure before calling UseIdentity and UseFacebookAuthentication or similar authentication scheme middleware. 請設定中介軟體來轉送 X-Forwarded-ForX-Forwarded-Proto 標頭:Configure the middleware to forward the X-Forwarded-For and X-Forwarded-Proto headers:

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

app.UseIdentity();
app.UseFacebookAuthentication(new FacebookOptions()
{
    AppId = Configuration["Authentication:Facebook:AppId"],
    AppSecret = Configuration["Authentication:Facebook:AppSecret"]
});

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

預設只會信任在 localhost (127.0.0.1, [::1]) 上執行的 Proxy。Only proxies running on localhost (127.0.0.1, [::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:

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 init 指令碼,會在系統啟動時將 Nginx 執行為精靈。The installer creates a systemd init script that runs Nginx as daemon on system startup. 請遵循 Nginx:Official Debian/Ubuntu packages (官方 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 以將要求轉送至您的 ASP.NET Core 應用程式,請修改 /etc/nginx/sites-available/defaultTo configure Nginx as a reverse proxy to forward 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:

server {
    listen        80;
    server_name   example.com *.example.com;
    location / {
        proxy_pass         http://localhost: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;
    }
}

當沒有任何與 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 which 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://localhost:5000 的 Kestrel。Nginx forwards the matching requests to Kestrel at http://localhost:5000. 如需詳細資訊,請參閱 nginx 如何處理要求 (英文)。See How nginx processes a request for more information. 若要變更 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.4 節See rfc7230 section-5.4 for more information.

建立 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 that 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+C 關閉應用程式。When done testing the app, shut the app down with Ctrl+C at the command prompt.

監視應用程式Monitor the app

伺服器已設定完成,可將對 http://<serveraddress>:80 發出的要求轉送給在位於 http://127.0.0.1:5000 的 Kestrel 上執行的 ASP.NET Core 應用程式。The server is setup 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 is an example 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

如果設定不是使用 www-data 這個使用者,就必須先建立這裡所定義的使用者,並授與適當的檔案擁有權。If the user www-data isn't used by the configuration, the user defined here must be created first and given proper ownership for 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 在管理員設定檔 (systemd-system.confsystem.conf.dsystemd-user.confuser.conf.d) 的預設值為 DefaultTimeoutStopSecTimeoutStopSec 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_ENVIRONMENT 設定為 "Production" 會導致搜尋 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>"

儲存檔案並啟用服務。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 並透過 systemd 管理 Kestrel 之後,Web 應用程式便已完全設定妥當,而從本機電腦瀏覽器透過 http://localhost 即可存取它。With 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 amount 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 cookieThis 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 伺服器的預設設定 (視平台而定通常為 4K 或 8K),下列指示詞需要調整。If the app requires request header fields longer than permitted by the proxy server's default settings (typically 4K or 8K depending on the platform), the following directives require adjustment. 要套用的值會因案例而異。The values to apply are scenario-dependent. 如需詳細資訊,請參閱您的伺服器文件。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 a 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 are not in use. 簡單的防火牆 (ufw) 提供命令列介面供設定防火牆,為 iptables 提供前端。Uncomplicated firewall (ufw) provides a front end for iptables by providing a command line interface 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

  • 藉由指定由受信任憑證授權單位 (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. 範例包括選擇更強的加密,重新導向 HTTPS 到 HTTP 的所有流量。Examples include choosing a stronger cipher and redirecting all traffic over HTTP to HTTPS.

  • 新增 HTTP Strict-Transport-Security (HSTS) 標頭可確保用戶端提出的所有後續要求都會透過 HTTPS。Adding an HTTP Strict-Transport-Security (HSTS) header ensures all subsequent requests made by the client are over HTTPS.

  • 如果未來將會停用 HTTPS,請不要新增 HSTS 標頭,或是選擇適當的 max-ageDon't add the HSTS header or chose an appropriate max-age if HTTPS will be disabled in the future.

新增 /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/Proxy.conf 組態檔。Edit the /etc/nginx/nginx.conf configuration 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;
    keepalive_timeout 29; # Adjust to the lowest possible value that makes sense for your use case.
    client_body_timeout 10; client_header_timeout 10; send_timeout 10;

    upstream hellomvc{
        server localhost:5000;
    }

    server {
        listen *:80;
        add_header Strict-Transport-Security max-age=15768000;
        return 301 https://$host$request_uri;
    }

    server {
        listen *:443    ssl;
        server_name     example.com;
        ssl_certificate /etc/ssl/certs/testCert.crt;
        ssl_certificate_key /etc/ssl/certs/testCert.key;
        ssl_protocols TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
        ssl_ecdh_curve secp384r1;
        ssl_session_cache shared:SSL:10m;
        ssl_session_tickets off;
        ssl_stapling on; #ensure your cert is capable
        ssl_stapling_verify on; #ensure your cert is capable

        add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
        add_header X-Frame-Options DENY;
        add_header X-Content-Type-Options nosniff;

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

保護 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/html"。With the nosniff option, if the server says the content is "text/html", the browser renders it as "text/html".

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

sudo nano /etc/nginx/nginx.conf

新增行 add_header X-Content-Type-Options "nosniff"; 並儲存檔案,然後重新啟動 Nginx。Add the line add_header X-Content-Type-Options "nosniff"; and save the file, then restart Nginx.

其他資源Additional resources