【问题标题】:Nginx: How to set headers for all the files under a specific folderNginx:如何为特定文件夹下的所有文件设置标题
【发布时间】:2020-10-09 21:33:38
【问题描述】:

假设我的应用程序在文件所在的位置

https://myapp.com/v1/assets/images/*.jpg

https://myapp.com/v1/assets/js/*.jpg

我想添加一条规则,将 no-cache 标头设置为 /assets 下的任何内容

我相信我现在能做的就是

 location ~ .*assets/js/.*$ {
  add_header Cache-Control "public, max-age=0, no-store";
}

location ~ .*assets/images/.*$ {
  add_header Cache-Control "public, max-age=0, no-store";
}

但这似乎不起作用,如果我在资产下有许多其他文件夹,我将需要添加一个单独的规则。

我可以将所有内容分组到一个模式中,以便 /assets/* 下的任何内容都有该标题吗?

谢谢

【问题讨论】:

    标签: nginx browser-cache nginx-reverse-proxy nginx-config


    【解决方案1】:

    这可以通过map 指令来完成:

    map $uri $cache_control {
        ~/assets/(images|js)/    "no-cache, no-store, must-revalidate";
    }
    server {
        ...
        add_header Cache-Control $cache_control;
        ...
    }
    

    如果您的 URI 与正则表达式不匹配,$cache_control 变量将具有空值,并且 nginx 不会将该标头添加到其响应中。但是还有其他 nginx 指令可能会影响 Cache-Control 标头,即 expires。如果你的配置中有expires <value>; 之类的东西,你可以使用两个map 块:

    map $uri $cache_control {
        ~/assets/(images|js)/    "no-cache, no-store, must-revalidate";
    }
    map $uri $expire {
        ~/assets/(images|js)/    off;
        default                  <value>;
    }
    server {
        ...
        expires $expire;
        add_header Cache-Control $cache_control;
        ...
    }
    

    看看this 的答案,不要对add_header 指令的行为感到惊讶。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-26
      • 1970-01-01
      • 1970-01-01
      • 2019-01-14
      • 1970-01-01
      • 2021-10-14
      • 2011-08-15
      • 2020-07-24
      相关资源
      最近更新 更多