<p>在Nginx中为静态文件设置浏览器缓存需精准匹配资源、分类型设定过期时间并补全Cache-Control头:用location ~* .(js|css|png|jpg|gif|woff2|svg)$或location ^~ /static/匹配,带哈希文件设expires 1y并加public, immutable, max-age=31536000;图片字体设expires 30d及public, max-age=2592000;HTML等动态内容用expires epoch和no-cache, must-revalidate, max-age=0;配置后须nginx -t校验、curl -I验证响应头、浏览器Network确认304或缓存加载。</p>
直接在 Nginx 的 location 块里用 expires 指令,就能为静态文件设置浏览器缓存时间。核心是匹配准确、策略合理、响应头完整。
别用模糊规则,避免误缓存 HTML 或接口响应:
~* 不区分大小写匹配后缀:比如 location ~* .(js|css|png|jpg|gif|woff2|svg)$
^~ 前缀匹配静态目录:比如 location ^~ /static/,性能更高且更安全location / { expires 1d; } 或 location ~ .html$,否则 HTML 页面可能被长期缓存缓存时长得看文件是否带版本标识(如哈希名),不是越长越好:
app.a1b2c3.js):设 expires 1y; 或 expires max;
expires 30d; 或 expires 6m;
logo.png):建议 expires 1h;~expires 1d;
expires epoch;(立即过期)或 expires -1;
expires 只生成基础缓存头,现代浏览器更依赖 Cache-Control,需手动补充:
add_header Cache-Control "public, immutable, max-age=31536000";
add_header Cache-Control "public, max-age=2592000";
add_header Cache-Control "no-cache, must-revalidate, max-age=0";
add_header 同级多次声明会覆盖,务必合并成一条改完不能直接上线,得确认响应头真实生效:
nginx -t 检查语法是否正确nginx -s reload 重载配置curl -I https://your-site/style.css 查看响应头,确认同时存在 Expires 和 Cache-Control
304(协商缓存生效)或直接从 memory/disk cache 加载