Nginx:如何为特定文件夹下的所有文件设置头部何为、头部、文件夹、文件

2023-09-04 01:55:16 作者:-黑色铅笔的默剧

假设我有一个应用程序,其中的文件位于

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

nginx 响应头中添加HSTS

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

我想添加一条规则,将无缓存头设置为/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/*下的所有内容都具有该标题?

谢谢

推荐答案

这可以通过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指令行为感到惊讶。