Nginx add_header 继承引起的问题分析及解决
在http部分配置了
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
在vhost中配置了
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
在nginx documentation 的 Module ngx_http_headers_module 中提到了一段话,大致意思就是,如果当前级别没有定义 add_header 则会继承上一级,如果定义了 add_header 则不会去理会上一级。
There could be several add_header directives. These directives are
inherited from the previous configuration level if and only if there
are no add_header directives defined on the current level.
意味着vhost如果定义了add_header,则不会从主配置中继承,由于子站点配置了HSTS,定义了add_header,所以主配置中的add_header不再生效。
那么解决也很简单,给vhost的配置单独配置一次add_header即可。
配置了HSTS产生了继承问题:
root@jp:~# curl -I https://32mb.net
HTTP/2 200
server: freenginx
date: Sun, 09 Feb 2025 02:00:18 GMT
content-type: text/html; charset=UTF-8
vary: Accept-Encoding
x-pingback: https://32mb.net/action/xmlrpc
alt-svc: h3=":443"; ma=86400
strict-transport-security: max-age=63072000; includeSubDomains; preload
vhost完成单独配置后测试结果如下。
root@jp:~# curl -I https://32mb.net
HTTP/2 200
server: freenginx
date: Sun, 09 Feb 2025 02:02:48 GMT
content-type: text/html; charset=UTF-8
vary: Accept-Encoding
x-pingback: https://32mb.net/action/xmlrpc
alt-svc: h3=":443"; ma=86400
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
x-content-type-options: nosniff
strict-transport-security: max-age=63072000; includeSubDomains; preload