Rootop 服务器运维与web架构

nginx add_header 指令在http{}段不生效的问题

目的:实现一个全局配置,让所有网站都响应一个指定头。

官方文档:https://nginx.org/en/docs/http/ngx_http_headers_module.html#add_header
其中一句
There could be several directives. These directives are inherited from the previous configuration level if and only if there are no directives defined on the current level.

可能会有多个指令。如果在当前配置级别没有定义这些指令,那么它们才会从上一级配置继承。

例子:

http {
	# 在http{}段里定义
    add_header X-From-Http "hello_http";

    server {
        # server{}段没有定义 add_header
        location / {
            root /usr/share/nginx/html;
        }
    }
}

在这种情况下:
server{} 没有定义 add_header,所以它会继承 http{} 里的配置。

响应头会包含 X-From-Http: hello_http。


另一个情况:
http {
    add_header X-From-Http "hello_http";

    server {
        add_header X-From-Server "hello_server";

        location / {
            root /usr/share/nginx/html;
        }
    }
}

在这种情况下:
server{} 已经定义了自己的 add_header。
根据文档所说,只要当前级别定义了 add_header 指令(不管后面添加的什么响应头),就不会继承上一级的。

所以最终响应头里只有:
X-From-Server: hello_server响应,而不会有 X-From-Http。

# 补充
只有响应下面这些状态码时add_header才会生效:
200, 201 (1.3.10), 204, 206, 301, 302, 303, 304, 307 (1.1.16, 1.0.13), or 308 (1.13.0). 

但是可以通过添加 always 参数实现无论什么状态码都添加。

最后通过 sed -i '/server_name/a # added by script' *.conf 这种批量方式实现在指定字符串的下一行添加。

原创文章,转载请注明。本文链接地址: https://www.rootop.org/pages/5620.html

作者:Venus

服务器运维与性能优化

评论已关闭。