由于项目是单页面应用,整个项目的JS文件其实包含了绝大部分的功能。项目发布时,会对文件名进行MD5重命名,因此以为缓存问题已被解决。但是在实际运行中,却发现总有发生没有请求最新文件的情况。那不就是项目的入口index.html被缓存了呗,得咱配置一个cache-control nocache吧!于是我GET到了一个新知识,因为这里面有误区。

NGINX基本配置

所有以 /mobile/ 开始的URL请求都会被定向到 mobile.html 文件,由其进行路由映射。

1
2
3
4
5
6
7
8
9
10
## server中已经指定root的path如下
# root /path/project/dist
location ^~ / {
access_log off;
expires 30d;
}

location ^~ /mobile/ {
try_files $uri$args /mobile.html;
}

配置Cache-Control 解决mobile.html的缓存问题

1
2
3
4
location ^~ /mobile/ {
add_header Cache-Control no-cache;
try_files $uri$args /mobile.html;
}

然而浏览器查看response-header, Cache-Control:max-age=2592000 仍然在里面,也就是说Cache-Control没生效

try_file会导致前面配置的 add_header 直接丢失

我开始怀疑是不是 Cache-Controltry_files 不搭?但是没有搜索到相关资料,那么是 add_headertry_files 不搭?确实,try_files匹配后,会直接进入匹配的location中的配置,我们在这里配置的都会被丢弃,ServerFault,也就是说我们要把这一段配置到 /mobile.html 中去:

1
2
3
4
5
6
7
location = /mobile.html {
add_header Cache-Control no-cache;
}

location ^~ /mobile/ {
try_files $uri$args /mobile.html;
}

这样,只会对mobile.html这个文件禁用缓存,其他的静态资源还是会被缓存起来,我们的目的达到了。