nginx add_header使用總結

基本使用

使用add_header允許在響應頭中新增自定義欄位。

官方文件地址:http://nginx。org/en/docs/http/ngx_http_headers_module。html

參考nginx官方文件,新增響應頭的方法如下:

nginx add_header使用總結

舉例:在conf檔案的server作用域中新增如下響應頭:

server { listen 80; # 其他配置。。。 # 允許跨域 add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods ‘GET, POST’; add_header Access-Control-Allow-Headers ‘DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization’; # 其他配置。。。}

儲存配置,重啟nginx伺服器,嘗試跨域請求nginx目錄下的json檔案,響應成功。

nginx add_header使用總結

遇到的坑:反向代理請求報錯

由於是在nginx server作用域下設定add_header,會對nginx反向代理的php/tomcat請求生效。

如果php程式碼中設定了

header(‘Access-Control-Allow-Origin: *’);

a

dd_header不會覆蓋而是追加

,響應頭會出現Access-Control-Allow-Origin多個定義錯誤。

解決方法:

在nginx location作用域中設定add_header。一般跨域請求的都是json檔案,僅對json檔案生效即可。

location ~ 。*\。(json)?$ { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods ‘GET, POST’; add_header Access-Control-Allow-Headers ‘DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization’; }

add_header總結

add_header 指令用於新增響應頭欄位,當且僅當狀態碼為200, 201, 204, 206, 301, 302, 303, 304, 307, 308有效。

add_header在其他狀態碼下也生效,可以加上always,add_header name value always。

當前作用域(http、server、location、location的if)沒有設定add_header的話,會繼承外層作用域的add_header設定。