Nginx 通过 Expires 和 Cache-Control 响应头控制静态资源缓存,需按资源类型精准配置:哈希文件设 expires 1y 并加 immutable;图片字体设 expires 30d;未版本化资源设 expires 1h~1d;HTML/API 设 expires epoch 并配 no-cache。
在 Nginx 中处理静态资源请求过期,本质是通过响应头控制浏览器是否复用本地缓存,而不是“让请求过期”。核心手段是设置 Expires 和 Cache-Control 响应头,且必须按资源类型区别配置,否则容易缓存 HTML 或接口数据导致内容 stale。
避免泛匹配干扰动态请求:
~* 正则匹配后缀(忽略大小写),覆盖主流类型:location ~* .(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|ttf|eot|webp)$ { ... }
^~ 匹配固定静态目录(如 /static/),性能更高、更安全:location ^~ /assets/ { ... }
location / 或 location ~ .html$ 里加 expires,否则 HTML 页面可能被强缓存过期策略取决于文件是否带版本标识(如构建时生成的哈希名):
app.a1b2c3.js):设为长期缓存,expires 1y; 或 expires max;
expires 30d;(约一个月)logo.png):建议 expires 1h;~expires 1d;,降低更新延迟风险expires epoch;(立即过期),并配合 add_header Cache-Control "no-cache, must-revalidate";
expires 指令只生成基础缓存头,现代浏览器更依赖 Cache-Control,且需语义明确:
add_header Cache-Control "public, immutable, max-age=31536000";immutable 告诉浏览器该资源不会变更,可跳过条件请求(F5 也不验证)add_header Cache-Control "public, max-age=2592000";
add_header 同级多次声明会覆盖,务必合并成一条改完别跳过检查步骤:
nginx -t 验证语法,再 nginx -s reload 重载curl -I https://your.site/style.css 查看响应头,确认同时存在 Expires 和 Cache-Control
proxy_pass 上游覆盖、静态文件是否真由 Nginx 直接提供(而非后端返回)