首頁  >  文章  >  運維  >  Nginx的add_header指令實例分析

Nginx的add_header指令實例分析

WBOY
WBOY轉載
2023-05-17 18:37:061497瀏覽

前言

大家都知道,nginx設定檔透過使用add_header指令來設定response header。

用curl查看一個站點的信息,發現返回的頭部與想像中的不一樣:

http/2 200
date: thu, 07 feb 2019 04:26:38 gmt
content-type: text/html; charset=utf-8
vary: accept-encoding, cookie
cache-control: max-age=3, must-revalidate
last-modified: thu, 07 feb 2019 03:54:54 gmt
x-cache: miss
server: cloudflare
...

主站點在nginx.conf中配置了hsts等header:

add_header strict-transport-security "max-age=63072000; preload";
add_header x-frame-options sameorigin;
add_header x-content-type-options nosniff;
add_header x-xss-protection "1; mode=block";

但回應頭部沒有這些header。除了常規的header,僅出現了一個配置配置在location中的header x-cache。

第一印像是cdn過濾了這些header?於是找cloudflare的文檔,沒發現會對這些進行處理。轉念一想,cdn過濾這些幹啥啊?吃飽了撐的啊?他們又不搞zheng審那一套!

問題轉移到nginx的配置上。打開google搜尋”nginx location add_header”,果然發現不少槽點。點開官網add_header的文檔,有這樣的描述(其他資訊已省略):

there could be several add_header directives. these directives are inherited from the previous level if and only if therectives are inherited from the previous level if and only if there are no add_er directives defined on the current level.

注意重點在「these directives are inherited from the previous level if and only if there are no add_header directives defined on the current level. 」。即:僅噹噹前層級中沒有add_header指令才會繼承父級設定。所以我的疑問就清晰了:location中有add_header,nginx.conf中的設定被丟棄了。

這是nginx的故意行為,說不上是bug或坑。但深入體會這句話,會發現更有意思的現象:僅最近一處的add_header起作用。 http、server和location三處皆可配置add_header,但運作的是最接近的配置,往上的配置都會失效。

但問題還不只如此。如果location中rewrite到另一個location,最後結果只會出現第二個的header。例如:

location /foo1 {
 add_header foo1 1;
 rewrite / /foo2;
}

location /foo2 {
 add_header foo2 1;
 return 200 "ok";
}

不管請求/foo1或/foo2,最終header只有foo2:

Nginx的add_header指令實例分析

儘管說得通這是正常行為,但總是讓人感覺有點勉強和不舒坦:server丟掉http配置,location丟掉server配置也就算了,但兩個location在同一層級啊!

不能繼承父級配置,又不想在目前區塊重複指令,解決方法可以用include指令。

以上是Nginx的add_header指令實例分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除