Nginx Virtual Host 中需在 server 块显式配置 expires 和 add_header Cache-Control 实现客户端缓存控制:静态资源设 long-term(如 expires 1y),HTML 或 API 禁用或短缓存,location 按文件类型精细化匹配,并避免继承干扰。
在 Nginx 的 Virtual Host(即 server 块)中配置客户端缓存过期时间,核心是通过 expires 指令和 add_header Cache-Control 协同控制浏览器行为,让静态资源在用户本地缓存更久,从而减少重复请求、降低服务器压力。
每个域名应独立配置,避免全局继承干扰。把 expires 放在对应 server 块里,而不是 http 或 upstream 中:
expires 1y;
expires -1; 或 expires epoch;
location 最优先,server 次之,http 最低 —— 所以明确写在 server 或关键 location 内更可靠expires 只设置 Expires 响应头,现代浏览器更依赖 Cache-Control。必须搭配 add_header 使用:
expires 1w; add_header Cache-Control "public, max-age=604800";
expires -1; add_header Cache-Control "no-cache, no-store, must-revalidate";
expires 10m; add_header Cache-Control "public, max-age=600, must-revalidate";
在 location 块中匹配后缀,比全局设置更安全高效:
location ~* .(js|css|png|jpg|gif|ico|svg|woff2?)$ { expires 1y; add_header Cache-Control "public, immutable"; }location = /favicon.ico { expires 7d; add_header Cache-Control "public"; }location /api/ { expires -1; add_header Cache-Control "no-cache"; }Nginx 配置有作用域优先级,容易因继承导致意外行为:
http 块写了 expires 1h,而某个 server 块没声明,则该站点会继承 1 小时server 块显式写了 expires 1d,就完全覆盖上级设置location 再写 expires epoch,则该路径下所有响应强制不缓存server 块顶层或关键 location 显式声明,不依赖隐式继承