NGINX配置无法禁止JSON/JS/CSS文件缓存,求排查解决
NGINX禁止缓存JSON/JS/CSS文件无效的问题修复
你当前的NGINX配置尝试禁止缓存JSON、JS、CSS文件,但浏览器仍从磁盘缓存加载这些文件,原配置如下:
server { listen 0.0.0.0:80; root /usr/share/nginx/html; proxy_connect_timeout 300; proxy_send_timeout 300; proxy_read_timeout 300; send_timeout 300; location / { try_files $uri $uri/ /index.html; } location ~* /.(css|js|json)$ { expires -1; add_header Cache-Control:no-store, no-cache; } }
配置中的两处关键错误
- 正则匹配规则错误:
location ~* /.(css|js|json)$里的路径写法错误,多了不必要的斜杠,且.在正则中是通配符,需要转义为\.。正确的匹配规则应该是~* \.(css|js|json)$,这样才能精准匹配后缀为css、js、json的文件。 - add_header语法错误:
add_header Cache-Control:no-store, no-cache;的格式不对,冒号应改为空格,且Header值需要用双引号包裹。正确写法是add_header Cache-Control "no-store, no-cache, must-revalidate";。
修正后的完整配置
server { listen 0.0.0.0:80; root /usr/share/nginx/html; proxy_connect_timeout 300; proxy_send_timeout 300; proxy_read_timeout 300; send_timeout 300; location / { try_files $uri $uri/ /index.html; } # 精准匹配禁止缓存的文件类型 location ~* \.(css|js|json)$ { expires -1; add_header Cache-Control "no-store, no-cache, must-revalidate"; add_header Pragma "no-cache"; # 兼容HTTP/1.0老浏览器 add_header Expires "Thu, 01 Jan 1970 00:00:00 GMT"; # 明确设置过期时间为过去 } }
验证方法
- 重启NGINX服务:
nginx -s reload(先执行nginx -t验证配置无语法错误) - 打开浏览器开发者工具(F12),切换到Network面板,刷新页面后查看对应文件的Response Headers,确认:
Cache-Control包含no-store, no-cacheExpires显示为过去的时间点
内容的提问来源于stack exchange,提问作者BoazYaari
相关产品推荐
相关产品推荐

