nginx 配置,使用 if 判断 add_header,其他 add_header 不见了

2017 年 4 月 25 日
 peesefoo

大体配置是这样,想实现带 mycookie 这个 cookie 的 php 页面,添加 Cache-Control 这个 http 头:

server {

    ...

    set $skip_cache 0;

    if ($http_cookie ~* "mycookie") {
        set $skip_cache 1;
    }
    
    location ~ [^/]\.php(/|$) {
        
        add_header X-Frame-Options "SAMEORIGIN";
        add_header X-Content-Type-Options "nosniff";
        
        if ($skip_cache = 1) {
            add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";
        }
    }
}

发现加了下面这 3 行代码后, Cache-Control 头倒是出现了,但是 X-Frame-Options 和 X-Content-Type-Options 这两个 http 头不见了,删掉这 3 行代码后又出现:

if ($skip_cache = 1) {
    add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";
}
7771 次点击
所在节点    程序员
11 条回复
julyclyde
2017 年 4 月 25 日
有一些指令的特性是这样的,只能在同一层内生效
所以你大概可以明白 fastcgi.conf 和 fastcgi_params 文件的用途了吧
rrfeng
2017 年 4 月 25 日
if-is-evil
peesefoo
2017 年 4 月 25 日
@rrfeng 测试了一下,如果不用 if ,仅仅添加:
add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";

X-Frame-Options 和 X-Content-Type-Options 这两个头也会消失。
crystom
2017 年 4 月 25 日
add_header 是数组,子块里有就会覆盖所有
rrfeng
2017 年 4 月 25 日
location ~ [^/]\.php(/|$) {

add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";
}

这样也会只有最后一个?
peesefoo
2017 年 4 月 25 日
@rrfeng 再看了一下,有三个,抱歉,上面说法有误。
Mitt
2017 年 4 月 25 日
尝试加 always 参数
```
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
```
PS: 网上查的解决方案。 Nginx > 1.7.5
msg7086
2017 年 4 月 25 日
nginx 里使用 if 判断,出问题不稀奇。
isCyan
2017 年 4 月 26 日
crystom 的回答应该是正解
ryd994
2017 年 4 月 26 日
if is evil
spacewander
2017 年 4 月 26 日
这事还真不好怪在 if 头上。
add_header 定义在下一级的会覆盖上一级的。你可以试试在 server 级别定义 add_header 看看。
一般遇到纠结于 Nginx 配置的人,我都会安利 lua-nginx-module 。可以省下不少 corner case 的精力。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/357346

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX