假设我有一个应用程序,其中的文件位于
https://myapp.com/v1/assets/images/*.jpg
和
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
指令行为感到惊讶。