小心Nginx的add_header指令

栏目: 服务器 · Nginx · 发布时间: 6年前

内容简介:转载请注明文章出处:昨天无聊用主站点在

转载请注明文章出处: https://tlanyan.me/be-careful-with-nginx-add_header-directive/

昨天无聊用 curl 查看一个站点的信息,发现返回的头部与想象中的不一样:

HTTP/2 200
date: Thu, 07 Feb 2019 04:26:38 GMT
content-type: text/html; charset=UTF-8
vary: Accept-Encoding, Cookie
cache-control: max-age=3, must-revalidate
last-modified: Thu, 07 Feb 2019 03:54:54 GMT
X-Cache: Miss
server: cloudflare
...

主站点在 nginx.conf 中配置了HSTS等header:

add_header Strict-Transport-Security "max-age=63072000; preload";
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";

但响应头部没有这些header。除了常规的header,仅出现了一个配置配置在 location 中的header X-Cache

第一印象是CDN过滤了这些header?于是找 Cloudflare 的文档,没发现会对这些进行处理。转念一想,CDN过滤这些干啥啊?吃饱了撑的啊?他们又不搞zheng审那一套!

问题转移到Nginx的配置上。打开Google搜索”nginx location add_header”,果然发现不少槽点。点开官网 add_header 的文档,有这样的描述(其他信息已省略):

There could be several add_header directives. These directives are inherited from the previous level if and only if there are no add_header directives defined on the current level.

注意重点在 “These directives are inherited from the previous level if and only if there are no add_header directives defined on the current level. ” 。即: 仅当当前层级中没有 add_header 指令才会继承父级设置 。所以我的疑问就清晰了: location 中有 add_headernginx.conf 中的配置被丢弃了。

这是 Nginx 的故意行为,说不上是bug或坑。但深入体会这句话,会发现更有意思的现象:仅最近一处的 add_header 起作用。 httpserverlocation 三处均可配置 add_header ,但起作用的是最接近的配置,往上的配置都会失效。

但问题还不仅于此。如果 locationrewrite 到另一个 location ,最后结果仅出现第二个的header。例如:

location /foo1 {
    add_header foo1 1;
    rewrite / /foo2;
}

location /foo2 {
    add_header foo2 1;
    return 200 "OK";
}

不管请求 /foo1 还是 /foo2 ,最终header只有 foo2

小心Nginx的add_header指令

尽管说得通这是正常行为,但总让人感觉有点勉强和不舒坦: server 丢掉 http 配置, location 丢掉 server 配置也就算了,但两个 location 在同一层级啊!

不能继承父级配置,又不想在当前块重复指令,解决办法可以用 include 指令。

参考

  1. Nginx Module ngx_http_headers_module
  2. Nginx add_header configuration pitfall
  3. Be very careful with your add_header in Nginx! You might make your site insecure
  4. add_header directives in location overwriting add_header directives in server
  5. nginx 配置之 add_header 的坑

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Head First Python

Head First Python

Paul Barry / O'Reilly Media / 2010-11-30 / USD 49.99

Are you keen to add Python to your programming skills? Learn quickly and have some fun at the same time with Head First Python. This book takes you beyond typical how-to manuals with engaging images, ......一起来看看 《Head First Python》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

SHA 加密
SHA 加密

SHA 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具