• 请不要在回答技术问题时复制粘贴 AI 生成的内容
peesefoo
V2EX  ›  程序员

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

  •  
  •   peesefoo · Apr 25, 2017 · 8049 views
    This topic created in 3485 days ago, the information mentioned may be changed or developed.

    大体配置是这样,想实现带 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";
    }
    
    11 replies  •  2017-04-26 22:43:40 +08:00
    julyclyde
    julyclyde
    Apr 25, 2017
    1
    有一些指令的特性是这样的,只能在同一层内生效
    所以你大概可以明白 fastcgi.conf 和 fastcgi_params 文件的用途了吧
    rrfeng
    rrfeng
    Apr 25, 2017
    2
    if-is-evil
    peesefoo
    peesefoo
    OP
    Apr 25, 2017
    3
    @rrfeng 测试了一下,如果不用 if ,仅仅添加:
    add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";

    X-Frame-Options 和 X-Content-Type-Options 这两个头也会消失。
    crystom
    crystom
    Apr 25, 2017
    4
    add_header 是数组,子块里有就会覆盖所有
    rrfeng
    rrfeng
    Apr 25, 2017
    5
    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
    peesefoo
    OP
    Apr 25, 2017
    6
    @rrfeng 再看了一下,有三个,抱歉,上面说法有误。
    Mitt
    Mitt
    Apr 25, 2017
    7
    尝试加 always 参数
    ```
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    ```
    PS: 网上查的解决方案。 Nginx > 1.7.5
    msg7086
    msg7086
    Apr 25, 2017
    8
    nginx 里使用 if 判断,出问题不稀奇。
    isCyan
    isCyan
    Apr 26, 2017 via Android
    9
    crystom 的回答应该是正解
    ryd994
    ryd994
    Apr 26, 2017 via Android
    10
    if is evil
    spacewander
    spacewander
    Apr 26, 2017 via Android
    11
    这事还真不好怪在 if 头上。
    add_header 定义在下一级的会覆盖上一级的。你可以试试在 server 级别定义 add_header 看看。
    一般遇到纠结于 Nginx 配置的人,我都会安利 lua-nginx-module 。可以省下不少 corner case 的精力。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4245 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 07:48 · PVG 15:48 · LAX 23:48 · JFK 02:48
    ♥ Do have faith in what you're doing.