博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
小心Nginx的add_header指令
阅读量:7218 次
发布时间:2019-06-29

本文共 1637 字,大约阅读时间需要 5 分钟。

转载请注明文章出处:

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

HTTP/2 200date: Thu, 07 Feb 2019 04:26:38 GMTcontent-type: text/html; charset=UTF-8vary: Accept-Encoding, Cookiecache-control: max-age=3, must-revalidatelast-modified: Thu, 07 Feb 2019 03:54:54 GMTX-Cache: Missserver: 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

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

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

参考

你可能感兴趣的文章
Web设计的速查卡(转)
查看>>
数据结构之哈夫曼树
查看>>
hdu1038
查看>>
CentOS 6.4下Zabbix的安装配置
查看>>
前端开发注意的问题 ,浏览器兼容性
查看>>
centos和redhat下 uwsgi配置
查看>>
Markdown 学习笔记
查看>>
vue-element-admin 多层路由问题
查看>>
Css问题 margin float 文档流 背景图底部充满
查看>>
JS match() 方法 使用
查看>>
关于shopee平台接口(php)对接示例
查看>>
BNU OJ 51000 BQG's Random String
查看>>
PAT (Advanced Level) 1044. Shopping in Mars (25)
查看>>
hdu 1531 King
查看>>
***R
查看>>
Linux 源码编译安装mysql
查看>>
取消手机端页面长按图片出现保存或者图片被打开的方法
查看>>
关于图片居中问题
查看>>
并发下的死锁问题
查看>>
Winserver下的Hyper-v “未在远程桌面会话中捕获到鼠标”
查看>>