返回上一頁

NGINX 設定檔整理及說明

文件日期:2022/12/28

文件內容除了整理 NGINX 設定之外,也同時描述如何透過 Container 管理 NGINX,如果是 On Premise 以 Linux VM 或裸機安裝可跳過 Container 安裝說明。唯部分設定章節會以 docker compose 來描述主機間的關係。

以下說明內容基於 Linux 進行說明,不適用 Windows 平台,在官方文件 NGINX for Windows 中第一段直接說明: high performance and scalability should not be expected.。

相關測試的設定檔及範例程式碼放在: https://git.example.com/gary/nginx-poc



安裝 NGINX

手動安裝

相關安裝指令以 Debian-based 的 apt-get 呈現, 在不同發行版上應視需要改用 yum 或 rpm 進行安裝。

由於 Debian, Ubuntu 及 Rocky Linux 使用套件管理工具(a.k.a. apt-get, yum...)安裝 NGINX 有版本相對落後以及 --with-debug 參數打開的情形,建議以原始碼編譯的方式安裝 NGINX。

文件撰寫當下, 使用 Rocky Linux 使用 yum 安裝的版本是 1.18.0, docker hub 上的 latest tag pull 下來的版本為 1.23.2,最新版的 source code 為 1.23.3。 同時 Rocky Linux 使用的 OpenSSL 為 2020 年的 1.1.1f (Debian 為 1.1.1n,同時期最新版為 1.1.1s)。

以下指令說明了如何從 NGINX 原始碼編譯並進行安裝,同時安裝 3rd-party 的 headers-more 模組。

部分功能需要手動下載原始碼進行編譯, wget 版本號調整時, tar 指令需對應修改, cd 至解壓縮出來的 nginx 目錄以及 ./configure 指令指向的路徑也須對應修改。

apt-get update && apt-get install curl wget build-essential -y 

mkdir /src && cd /src 

# 檢查 https://nginx.org/download/ 是否有新版
wget https://nginx.org/download/nginx-1.23.3.tar.gz 
# 檢查 https://github.com/PCRE2Project/pcre2/releases 是否有新版
wget https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.42/pcre2-10.42.tar.gz  
# 檢查 https://github.com/madler/zlib/releases/ 是否有新版
wget https://github.com/madler/zlib/releases/download/v1.2.13/zlib-1.2.13.tar.gz 
# 檢查 https://github.com/openssl/openssl/tags 是否有新版, 須注意目前版本的 NGINX 要使用 1.x.x 版的 OpenSSL
wget https://github.com/openssl/openssl/archive/refs/tags/OpenSSL_1_1_1s.tar.gz 
# 檢查 https://github.com/openresty/headers-more-nginx-module/tags 是否有新版
wget https://github.com/openresty/headers-more-nginx-module/archive/refs/tags/v0.34.tar.gz -O headers-more-nginx-module-0.34.tar.gz 

tar -zxvf nginx-1.23.3.tar.gz 
tar -zxvf pcre2-10.42.tar.gz 
tar -zxvf zlib-1.2.13.tar.gz 
tar -zxvf OpenSSL_1_1_1s.tar.gz  
tar -zxvf headers-more-nginx-module-0.34.tar.gz 
 
cd nginx-1.23.3 

./configure --prefix=/etc/nginx \
    --with-pcre=../pcre2-10.42/ \
    --with-zlib=../zlib-1.2.13/ \
    --with-openssl=../openssl-OpenSSL_1_1_1s \
    --add-module=../headers-more-nginx-module-0.34/ \
    --with-compat \
    --with-file-aio \
    --with-threads \
    --with-pcre-jit \
    --with-http_addition_module \
    --with-http_auth_request_module \
    --with-http_dav_module \
    --with-http_flv_module \
    --with-http_gunzip_module \
    --with-http_gzip_static_module \
    --with-http_mp4_module \
    --with-http_random_index_module \
    --with-http_realip_module \
    --with-http_secure_link_module \
    --with-http_slice_module \
    --with-http_ssl_module \
    --with-http_stub_status_module \
    --with-http_sub_module \
    --with-http_v2_module \
    --with-stream \
    --with-stream_realip_module \
    --with-stream_ssl_module \
    --with-stream_ssl_preread_module \
    --without-mail_pop3_module \
    --without-mail_imap_module \
    --without-mail_smtp_module

make && make install

上述指令在完成 ./configure 後,可以看到如下的 Configuration summary, 這部分資訊會需要記起來, 後續會用到

 Configuration summary
   + using threads
   + using PCRE2 library: ../pcre2-10.42/
   + using OpenSSL library: ../openssl-OpenSSL_1_1_1s
   + using zlib library: ../zlib-1.2.13/
 
   nginx path prefix: "/etc/nginx"
   nginx binary file: "/etc/nginx/sbin/nginx"
   nginx modules path: "/etc/nginx/modules"
   nginx configuration prefix: "/etc/nginx/conf"
   nginx configuration file: "/etc/nginx/conf/nginx.conf"
   nginx pid file: "/etc/nginx/logs/nginx.pid"
   nginx error log file: "/etc/nginx/logs/error.log"
   nginx http access log file: "/etc/nginx/logs/access.log"
   nginx http client request body temporary files: "client_body_temp"
   nginx http proxy temporary files: "proxy_temp"
   nginx http fastcgi temporary files: "fastcgi_temp"
   nginx http uwsgi temporary files: "uwsgi_temp"
   nginx http scgi temporary files: "scgi_temp"

有關 ./configure 的更多參數 ,可參考: http://nginx.org/en/docs/configure.html

以 Container 方式執行

此份文件後續 NGINX 有關的操作主要都以 Container 進行說明,以 Linux VM 或是 Linux 裸機進行安裝可參考 手動安裝。

直接使用 NGINX

docker run -d -p 80:80 -p 443:443 --name my-nginx nginx

透過 docker-compose 使用,先寫出一個簡單的 docker-compose.yml

version: "3.8"
services:
  ingress:
    image: "nginx"
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - type: bind
        source : ./nginx/conf.d
        target: /etc/nginx/conf.d

再透過 docker compose up 叫起來。

安裝 3rd-party 模組

依據 NGINX 官方映像的 Source Code 中 modules 的 README Adding third-party modules to nginx official image,可以透過官方映像加上 --build-arg 來選擇增加第三方模組。

使用這個方式來建置帶有 3rd-party 模組的自訂映像,好處是可以沿用既有的 Container 環境 (google 問題方便,不會有設定路徑無法對應問題),以及 Container 容量最佳化的優點。

以下使用 docker compose 來描述如何自訂第三方模組,內容可轉換為對應的 docker build 指令。

version: "3.8"
services:
  ingress-v2:
    build:
      context: ./docker-nginx/modules
      dockerfile: Dockerfile
      args:
        ENABLED_MODULES: headers-more
    image: nginx-with-headers-more:dev
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - type: bind
        source : ./nginx/nginx.conf
        target: /etc/nginx/nginx.conf
      - type: bind
        source : ./nginx/conf.d
        target: /etc/nginx/conf.d
      - type: bind
        source : ./cert
        target: /etc/nginx/cert

由於此方法建置出來的第三方模組都是以 --add-dynamic-module 作為建置指令,所以需要在 runtime 時指定 load_module , 並且 load_module 需在一開始執行時即載入,所以額外把 /etc/nginx/nginx.conf 做 bind-mount。

並在 nginx.conf 的最前面增加 load_module:

load_module /etc/nginx/modules/ngx_http_headers_more_filter_module.so;

文件只說 load_module 要放在 main 區域,實際上在 nginx.conf 中如果擺在 event 跟 http 中間,在執行時會出現如下錯誤:

 nginx: [emerg] "load_module" directive is specified too late in /etc/nginx/nginx.conf:13 

所以理解上,應該是放在 nginx.conf 的第一個 { 以前才可以。

實際驗證安裝容量,增加 header-more 這個第三方模組之後, Container 大小為 143MB, 如果使用手動安裝,即便使用 debian-slim 作為基礎映像, Container 大小仍然成長至 900 MB 左右。

NGINX 作為測試主機的入口,將子路徑導向 host 內不同的 Container

此規劃目的在達到以 container 為基礎架構的環境下,如何達到過往在同一台 IIS 上可以託管多個專案的 Web Application。

以下以 Ubuntu Linux 20.04 LTS 版搭配 Docker/Dockerd v20.10.21 版完成後續驗證。

環境架構如下:

flowchart TD
client -.-> INGRESS[[Reverse Proxy]]
subgraph  SERVICE-AP xx
    subgraph 專案 XXX
        INGRESS --> WebApp1([XXX_MYWEB])
        INGRESS --> WebApp2([XXX_ASPNETCORE_APP])
        INGRESS --> WebApp3([XXX_WebModule])
    end
    subgraph 其他專案 ...
        INGRESS ----> WebApp4([OTHERS_APP?])
        INGRESS ----> WebAppN([OTHER Web Apps?])
    end
end

此處建立一個模擬專案,以 NGINX 作為 Reverse Proxy,並使用 NGINX Container 與 docker compose 來達成。

專案結構如下:

├── ap1/
├── ap2/
├── docker-compose.yml
├── nginx
│   └── conf.d
│       └── default.conf
└── service-ap.sln

首先說明 docke compose 檔:

version: "3.8"
services:
  ap1:
    image: "ap1"
  ap2:
    image: "ap2"
  ingress:
    image: "nginx"
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - type: bind
        source : ./nginx/conf.d
        target: /etc/nginx/conf.d

此處為兩個模擬後續各專案 Web App 的 Container,分別為 AP1 以及 AP2, 兩個 Container 的 Docker Image 為 ap1 及 ap2。

另外有一個名為 ingress 的 Container, Docker Image 是 nginx,如此設定,可以讓 ingress 可以透過 ap1、ap2 的別名存取另外兩個服務,須注意是 services 下的 ap1, 不是 image: ap1,像是 nginx 在這個 yml 中別名為 ingress,這三個服務之間可以透過 http://ap1/ 、 http://ap2/ 、 http://ingress/ 互相存取。

在 compose 內,一個 Container 的別名有多個,分別是 {ComposeName}-{ServiceName}-{N} 、 ServiceName 以及 ContainerId ,服務可透過別名互相存取,直接使用 docker run 指令跑起來的 container 要互相存取只能透過 IP。 別名及 IP 資訊可以透過 docker inspect 指令查詢得到。

測試互相存取可透過 docker exec 進去 container 後,以 curl 指令確認是否有通,container 內不見得有 ping 指令可用。

另外 ingress 還有進行 80, 443 port 的 port fowarding ,以及將當前 docker-compose 檔目錄下相對位置的 ./nginx/conf.d 目錄 mapping 到 container 內的 /etc/nginx/conf.d 目錄下。

Container 版的 NGINX 中, nginx.conf 位於 /etc/nginx/nginx.conf 中,其中最後一行為:

include /etc/nginx/conf.d/*.conf;

此行描述為引入 /etc/nginx/conf.d/ 下的所有 .conf 檔 故只要將 /etc/nginx/conf.d 與外部 mapping,就可以達到分專案有不同的 project.conf (避免龐大複雜的 conf 檔),以及可以版控設定檔的目的。

接著看到 ./nginx/conf.d 下的 default.conf 設定檔:

server {
    listen       80;
    listen  [::]:80;
    server_name  *.dev.example.com;

    proxy_set_header Host $http_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 $http_x_forwarded_proto;

    location /ap1/ {
        proxy_pass http://ap1/;
        #proxy_redirect /ap1 /;
        sub_filter '="/' '="/ap1/';
        sub_filter_once off;
    }

    location /ap2/ {
        proxy_pass http://ap2/;
        #proxy_redirect /ap2 /;
        sub_filter '="/' '="/ap2/';
        sub_filter_once off; 
    }

    location / {
        return 404 ' '; 
    }
}

其中四個 proxy_set_header 分別設定了 reverse proxy 會附加那些 Request Header 往後端 AP 送,像 X-Forwarded-For 就是作為 HTTP 標準,告知後端 AP 有經過 Reverse Proxy,以及來源 IP 是何者的標準標頭。

接著看到兩個 location /ap1/ 以及 location /ap2/ 區塊:

location /ap1/ {
    proxy_pass http://ap1/;
    sub_filter '="/' '="/ap1/';
    sub_filter_once off;
}

此處為告知 NGINX 需要將請求路徑中,以 /ap1/ 開頭的請求全部套用以下設定:

  • proxy_pass:導向到 ap1 這個 container 實體
  • sub_filter:將 response body 中的 ="/ 文字全部替換成 ="/ap1/
    • 此目的為將所有 script src 、style link、 a href 等路徑全部增加一層 /ap1/,避免後續頁面載入後其他資源的請求打到上層路徑,或是對系統內的超連結位置打到上層。
  • sub_filter_once off:全部取代

此時 client 端得請求路徑會是 此時 client 請求會像是 http://service-ap.example.com/ap1/ 或是 此時 client 請求會像是 http://service-ap.example.com/ap1/some/sub/paths/?and=some&query=strings

驗證站台的 source code 位於路徑: https://git.example.com/gary/containerized-service-ap

NGINX 作為主網域的入口,將不同子網域導向至不同 IP 或特定同一台主機的子路徑

驗證情境以 NGINX 作為 Reverse Proxy,將特定 zzz.serv.example.com 的請求導向至特定的 AP 主機的某個包含子路徑的網址 (http://example.com/zzz_myweb),並且當 zzz 實際上不存在主機上時回應 404 給使用者。

示意:

flowchart TD

ClientA --a.serv.example.com--> NGINX{{NGINX}}
ClientB --b.serv.example.com--> NGINX
ClientX --zzz.serv.example.com--> NGINX

NGINX --a.serv.example.com--> ServerA
NGINX --b.serv.example.com--> ServerB
NGINX --zzz.serv.example.com--> 404

驗證環境準備:

  1. Clinet
    • 個人開發機
  2. NGINX Server
    • Ubuntu Linux VM 上的一個 Container Instance
  3. AP Server
    • 此處以 AP14 替代實際的雲高主機

由於不是正式移轉,先在 client 中先將 NGINX Server 所在的 IP 以要測試的 domain 寫入在 hosts 裡面,模擬 dns server 已經將 *.serv.example.com 指向 NGINX 的情境。

以下為確認可行的完整 conf 檔內容:

server {
    listen       80;
    listen  [::]:80;
    server_name  aaa.serv.example.com;
    
    location / {
        proxy_set_header Host $http_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 $http_x_forwarded_proto;

        proxy_redirect /AAA_MYWEB/ /;
        proxy_pass http://192.168.116.14/AAA_MYWEB/;

        rewrite (?i)^/AAA_MYWEB/(.*)$ /$1 last;

        sub_filter '/AAA_MYWEB/' '/';
        sub_filter_once off;
    }
}

server {
    listen       80;
    listen  [::]:80;
    server_name  bbb.serv.example.com;
    
    location / {
        proxy_set_header Host $http_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 $http_x_forwarded_proto;

        proxy_redirect /BBB_MYWEB/ /;
        proxy_pass http://192.168.116.14/BBB_MYWEB/;

        rewrite (?i)^/BBB_MYWEB/(.*)$ /$1 last;

        sub_filter '/BBB_MYWEB/' '/';
        sub_filter_once off;
    }
}


server {
    listen       80;    
    listen  [::]:80;
    server_name  *.serv.example.com;
    
    location / {
        return 404 ' ';
    }

    # error_page  404              /404.html;
    # error_page   500 502 503 504  /50x.html;
}

後續以 config 檔內第一個 server 區段解說

server {
    listen       80;
    listen  [::]:80;
    server_name  aaa.serv.example.com;
    
    location / {

        proxy_set_header Host $http_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 $http_x_forwarded_proto;

        proxy_redirect /AAA_MYWEB/ /;
        proxy_pass http://192.168.116.14/AAA_MYWEB/;

        rewrite (?i)^/AAA_MYWEB/(.*)$ /$1 last;

        sub_filter '/AAA_MYWEB/' '/';
        sub_filter_once off;
    }
}
  • listen : 接聽 80 port
  • 當 server name :當請求為 aaa.serv.example.com 時走此規則
  • proxy_set_header :為設定 Reverse Proxy 相關資訊給後端 AP 辨識
  • proxy_redirect : 將所有帶有重新導向(301,302)的回應內的 /AAA_MYWEB/ 取代成 /
  • proxy_pass :為將當前請求導向至 http://192.168.116.14/AAA_MYWEB/
  • rewrite :網址複寫,將 /AAA_MYWEB/ 取代為 /
  • sub_filter :將回應內容內的 /AAA_MYWEB/ 取代為 / 避免後續靜態檔資源的請求以及超連結產生 /AAA_MYWEB/ 開頭的相對路徑
  • sub_filter_once off: 全部取代

NGINX 作為負載平衡

NGINX 與各 AP 主機之間的關聯如下圖:

flowchart TD
Client(Client) -.-> NGINX[[NGINX]]
NGINX --> service-ap-lb-1
NGINX -->service-ap-lb-2
NGINX -->service-ap-lb-3

以 docker compose 來描述主機間的關係,大約是如下的 yaml:

version: "3.8"
services:
  lb:
    image: "lb"
    deploy:
      replicas: 3
  ingress-v2:

設定 scale: 3 時被提示 scale is deprecated. 有需要使用 docker compose 請注意

在 conf.d 目錄中增加一組負載平衡的 upstream 以及 server 設定

upstream application {
    server service-ap-lb-1;
    server service-ap-lb-2;
    server service-ap-lb-3;
}

server {
    listen  80;
    server_name test-lb.serv.example.com;

    location / {
        proxy_pass http://application;
    }
}

此處有指定 server_name test-lb.serv.example.com;, client 需先設定好 host ,才能打 test-lb.serv.example.com 來進行測試

實際測試結果如上圖的 log ,如此設定確實達到分散 request 到多台的效果,但同一台 client 每次 request 都會被 NGINX 導向到不同的後端。

預設的負載平衡方式為[]加權輪詢(Weighted round robin )(https://zh.wikipedia.org/zh-tw/%E5%8A%A0%E6%AC%8A%E8%BC%AA%E8%A9%A2%E7%AE%97%E6%B3%95) , 效果與指定

讓同一個 Client 每次都連到同一個後端的 AP

ip_hash

將來自同一個 IP 的 Client 每次都導向同一個後端,除非該後端不可用

upstream application {
    ip_hash;

    server service-ap-lb-1;
    server service-ap-lb-2;
    server service-ap-lb-3;
}

實際測試,同一個 client 都打向同一個後端。 但此作法在內部使用者與地端建置,以及雲端服務對不特定客戶時有用,如果是服務放置在雲端,但服務的客戶在辦公地點只有一個對外 IP 時,將會把所有 User 的流量全部導向到同一個後端。

REF: http://nginx.org/en/docs/http/ngx_http_upstream_module.html#ip_hash

官方文件中提到的 sticky directive 是付費版的 NGINX Plux 提供的功能。

免費版可考慮的有:

不過發行日期最少都在七年以上,暫時不評估。

NGINX 設定符合 FIPS 140 標準的 SSL/TLS 組態

設定 NGINX 接聽 443 PORT,以及限制高強度 Cipher Suites

測試環境可透過下列指令簽出自簽憑證,正式環境應取得正式的憑證。

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout cert.key -out cert.crt

回答完相關問題後,會在當前目錄下取得 cert.key 以及 cert.crt 兩個檔案,分別為私鑰(*.key) 以及憑證 (*.crt)。

將這兩個檔案放置至 nginx 主機上,此處以 docker-compose.yml 表示,將檔案所在的目錄 bind mount 到 NGINX Container 的 /etc/nginx/cert。建置時以相關憑證檔的實際路徑替換。

version: "3.8"
services:
  ingress:
    image: "nginx"
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - type: bind
        source : ./cert
        target: /etc/nginx/cert

調整 NGINX Conf 設定

server {
    listen       80;
    listen  [::]:80;
    listen       443 ssl;
    listen  [::]:443 ssl;

    server_name  example.com;

    ssl_certificate /etc/nginx/cert/cert.crt;
    ssl_certificate_key /etc/nginx/cert/cert.key;

    ssl_protocols TLSv1.2 TLSv1.3;

    # 只允許 FIPS, 但阻擋 aNULL & MD5 & TLS1 & TLS1.1 ciphers
    ssl_ciphers "FIPS:!aNULL:!MD5:!TLSv1.0:!TLSv1.1"; 
    
    #只允許列出的兩個 ECDHE ciphers 的情境,請註解上方的 FIPS 設定,並取消註解此行
    #ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256"; 

}
  • listen:增加接聽 443 port
  • ssl_certificate : 憑證檔路徑
  • ssl_certificate_key :私鑰路徑
  • ssl_protocols :允許使用的 TLS 版本
    • NGINX 1.9.x 以上預設啟用為 TLSv1.0 ~ TLSv1.2,另外在 Linux 下可啟用 TLSv1.3,此處將設定寫為啟用 TLSv1.2、TLSv1.3
  • ssl_ciphers :允許啟用的加密套件
    • 原則啟用,例外排除: FIPS:!aNULL:!MD5:!TLSv1.0:!TLSv1.1
      • 演算法之間以 : 隔開,排除的演算法以 ! 開頭
      • 此寫法為啟用 FIPS 140-2 允許的加密演算法,但排除 aNULL、MD5、TLSv1.0、TLSv1.1 等演算法。但其實當前版本的 openssl 套件, FIPS 本身即不包含 aNULL、MD5。 以 nmap 查詢可確認下列加密套件為啟用中
      • 僅白名單啟用 ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256,只允許兩個 ECDHE 演算法啟用,這兩個演算法可通過 SSL Labs 的 測試 以 nmap 查詢,可看到 TLSv1.2 只剩下兩個套件為啟用中

要確認有哪些加密套件可以使用,可用下列指令查詢:

openssl ciphers -v 

將所有 HTTP 流量強制導向至 HTTPS

將原本 conf 內,server 區段接聽 80 port 相關設定註解掉

server {
    #listen       80;
    #listen  [::]:80;
    listen       443 ssl;
    listen  [::]:443 ssl;

    # ... 其餘略過 ...
}

並增加一個 server 區段,只接聽 80 port,並直接回應 301

server {
    listen       80;
    listen  [::]:80;

    return 301 https://$host$request_uri;
}

完成重啟後,驗證 http 流量透過 301 直接轉向至 https

處理 SignalR 使用的 ws:\\ 及 wss:\\ 流量

由於公文系統有使用到 WebSocket 技術, NGINX 在作為 Reverse Proxy 或 Load Balancer 時,需將 WebSocket 相關的流量導向至後方的 AP 主機。

實作一個使用 SignalR 做的陽春聊天室,聊天室參考自: https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-6.0&tabs=visual-studio-code

確認聊天室直接執行可正常運作後,開始設定 NGINX,以下假定這個聊天室的 AP Server 有一個 http://chatroom/ 的網址。

增加 NGINX conf 的 location,確認到可正常開出頁面:

location /chatroom/ {
    proxy_pass http://chatroom/;
    sub_filter '="/' '="/chatroom/';
    sub_filter_once off; 
}

此時的 SignalR 是無法正常運作的,可以在瀏覽器的 Devtools Console 中看到類似這樣的錯誤。

接著開始進行 WebSocket 相關的設定:

  • 在 conf 檔中, Server 區段外面,增加以下設定:
    map $http_upgrade $connection_upgrade{
        default upgrade;
        ''      close;
    }
    
  • 在 server 區段內,增加 proxy_http_version ,以及以下 proxy_set_header :
    server {
    
        # ... 前略 ...
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        # ... 前略 ...
    }
    

完成後重啟 NGINX , 並確認 SignalR 可正常運作,且 Devtools 看到的是 101 Switching Protocols。

PS:此情境中, chatroom 這個 .NET 6 站台,並未啟用 HTTPS 連線。 HTTPS 連線只到 NGINX 就結束, NGINX 與 後端 AP 之間是使用 HTTP 流量溝通。

此模擬情境以 docke compose 描述表達為:

services:
  chatroom:
    image: "ws"
  ingress:
    image: "nginx"

NGINX 操作回應標頭

增加標頭

在作為 Reverse Proxy 操作要求標頭,將資訊附加至標頭並轉送至後端伺服器時,使用的是 proxy_set_header,要附加回應標頭至 client 端,可以使用 add_header , add_header 的參數為:

add_header {name} {value} {*always};

例如

add_header X-Hi "Hello World!";

則可以在回應標頭中看到 X-Hi: Hello World!

但須注意的是未指定 StatusCode 時, add_header 只在 200, 201, 204, 206, 301, 302, 303, 304, 307, 308 的回應中被附加,如果在所有的回應狀態都要附加標頭,則可在 最後一個欄位填寫 always。

add_header Hi "Hello World!" always;

符合 SecurityHeaders 測試要求的設定

以下設定,可通過 https://securityheaders.com/ 要求,並取得 A+ 的 Report。

#add_header Content-Security-Policy "default-src 'self'" # 注意! 這個 Header得在 IIS 的 Default Web Site 設定, 不能在 NGINX
add_header X-Frame-Options	"SAMEORIGIN"
add_header X-Content-Type-Options	"nosniff"
add_header X-XSS-Protection	"1"
add_header Referrer-Policy	"strict-origin-when-cross-origin"
add_header Permissions-Policy	"geolocation=(),microphone=(),camera=()"
add_header Strict-Transport-Security	"max-age=31536000;includeSubDomains"

其中 Content-Security-Policy 必須 在 IIS 端做設定,因公文系統的 Content-Security-Policy 有使用到 nonce,不同的模組之間 nonce 以及允許的 HOST 也不同。

移除標頭

需先確認有安裝 headers-more 模組 ,使用官方的 NGINX Image 或是安裝時未掛模組,將會在設定檔異動後無法啟動 NGINX,並可能出現以下錯誤:

  1. 直接套用動態模組的設定檔
    nginx: [emerg] dlopen() "/path/to/modules/ngx_http_headers_more_filter_module.so" failed (/path/to/modules/ngx_http_headers_more_filter_module.so: cannot open shared object file: No such file or directory) in /etc/nginx/nginx.conf:8
    
  2. 直接在 conf 中使用了 more_clear_headers 指令,未指定載入動態模組或未安裝 headers-more 模組:
    nginx: [emerg] unknown directive "more_clear_headers" in /etc/nginx/conf.d/default.conf:42
    

在 server 區段中增加 more_clear_headers 指令,要移除多個標頭時要指定多次:

server {
    # ... 前略 ... 
    # add header
    add_header X-Hi "hello world!" always; # add_header will append header when status code in 200 or 204, add `always` for any stats code

    # 可以移除 nginx 帶出來的 Server Header
    more_clear_headers 'Server';
    # 可以移除 backend 帶出來的 X-AP1 Header
    more_clear_headers 'X-AP1';

    # 看起來無法移除同一個設定檔下的 X-Hi Header....
    more_clear_headers 'X-Hi';

    # ... 後略 ... 
}

測試確認 Server 標頭可移除,後端 AP 夾帶的回應標頭可移除,但 NGINX conf 中自行指定的標頭 無法 移除。