歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> 【nginx】4xx,5xx 保持自定義header

【nginx】4xx,5xx 保持自定義header

日期:2017/3/1 12:15:34   编辑:關於Linux

問題

nginx使用中,如果請求返回的狀態code類似404或者50x這種,仍然返回自定義的header。

分析和解決

nginx文檔中關於 add_header的部分 有這麼一句

Adds the specified field to a response header provided that the response code equals 200, 201, 204, 206, 301, 302, 303, 304, or 307. A value can contain variables.

也就是說 add_header 一般是不會作用在 4xx,5xx的響應上的。

但是從 1.7.5版本之後可以使用 always關鍵字來解決,下面來測試下。

配置片段

    location /hello {
        add_header Access-Control-Allow-Origin * always;
        return 404;
    }

測試結果

curl -i  http://127.0.0.1:9999/hello

HTTP/1.1 404 Not Found
Server: openresty/1.9.3.1
Date: Mon, 01 Feb 2016 11:17:59 GMT
Content-Type: text/html
Content-Length: 174
Connection: keep-alive
Access-Control-Allow-Origin: *

可以看到測試成功。

拓展模塊

另外還可以使用 春哥寫的 headers-more-nginx-module 來做個事情,具體請參考文檔。

REF

http://serverfault.com/questions/418709/nginx-add-header-for-a-50-page
Copyright © Linux教程網 All Rights Reserved