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


问题

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

相关内容

    暂无相关文章