nginx add_header 的繼承陷阱:location 加一個標頭,安全標頭全不見

在 server 層設好安全標頭,某個 location 只多加一個 Cache-Control,結果那個路徑的安全標頭全部消失。原因是 add_header 的繼承規則,附實測與兩種修法。

在 server 層設好 X-Frame-Options 這些安全標頭,掃描工具也顯示首頁都有。過一陣子幫靜態檔加了快取標頭,再掃一次,/assets/ 底下的安全標頭全部不見了。

重現問題

設定檔只在 /assets/ 多加一行 Cache-Control:

server {
    listen 127.0.0.1:18080;
    root html;

    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    location / {
    }

    location /assets/ {
        add_header Cache-Control "public, max-age=31536000, immutable";
    }
}

首頁的標頭正常:

$ curl -sI http://127.0.0.1:18080/
HTTP/1.1 200 OK
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin

/assets/ 底下只剩新加的那一個:

$ curl -sI http://127.0.0.1:18080/assets/app.css
HTTP/1.1 200 OK
Cache-Control: public, max-age=31536000, immutable

測試環境:nginx 1.28.3。

原因:有自己的 add_header,就不繼承上層

nginx 文件的規則是:只有在目前這一層「完全沒有」add_header 時,才會繼承上一層的設定。

location / 裡沒有任何 add_header,所以繼承了 server 層的三個標頭。location /assets/ 有一行自己的 add_header,上層的三個就全部不算了。不是合併,是整組取代。

同樣的規則也適用於 proxy_set_header、fastcgi_param 等可以寫多次的指令。

> [!WARNING] > 這個問題不會出現錯誤訊息,nginx -t 也會通過。只能靠實際檢查回應標頭發現。

修法一:把共用標頭放進片段檔

把安全標頭寫成獨立的檔案:

# security-headers.conf
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

server 層和每個有自己 add_header 的 location 都 include 一次:

server {
    include security-headers.conf;

    location / {
    }

    location /assets/ {
        include security-headers.conf;
        add_header Cache-Control "public, max-age=31536000, immutable";
    }
}

結果四個標頭都在:

$ curl -sI http://127.0.0.1:18080/assets/app.css
HTTP/1.1 200 OK
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Cache-Control: public, max-age=31536000, immutable

這個做法所有版本都能用,缺點是新增 location 時要記得 include。

修法二:nginx 1.29.3 起的 add_header_inherit

nginx 1.29.3 新增了 add_header_inherit 指令,設成 merge 時,下層的 add_header 會加在上層的後面,不再取代:

http {
    add_header_inherit merge;
    ...
}

寫在 http 層會一路影響所有下層,除非某層重新設定。本文的測試環境是 1.28.3,沒有這個指令,這段沒有實測;使用前請先用 nginx -v 確認版本。

檢查清單

  • 每個有 add_header 的 location,都要確認安全標頭還在。
  • 用 curl -sI 逐一檢查主要路徑:首頁、靜態檔、API、上傳目錄。
  • always 參數讓錯誤頁(404、500)也帶上標頭,安全標頭建議都加。

關於作者

已發表 274 篇文章

留言

還沒有留言。有補充、疑問或不同做法,歡迎第一個留言。

發表留言

Email 不會公開,只用於回覆通知。

第一次留言需經審核,之後會直接顯示。