最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Nginx 如何在 Virtual Host 中配置客户端缓存过期时间减少服务器压力
时间:2026-09-04 19:43:48 编辑:袖梨 来源:一聚教程网
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 协同控制浏览器行为,让静态资源在用户本地缓存更久,从而减少重复请求、降低服务器压力。
直接在 server 块内按域名设置 expires
每个域名应独立配置,避免全局继承干扰。把 expires 放在对应 server 块里,而不是 http 或 upstream 中:
- 静态资源(如 JS/CSS/图片)建议设为长期缓存,例如
expires 1y; - HTML 页面或动态接口通常禁用缓存或设极短时间,例如
expires -1;或expires epoch; - 配置生效范围以
location最优先,server次之,http最低 —— 所以明确写在server或关键location内更可靠
配合 Cache-Control 实现精准控制
expires 只设置 Expires 响应头,现代浏览器更依赖 Cache-Control。必须搭配 add_header 使用:
- 强缓存(如 CDN 或静态资源):
expires 1w; add_header Cache-Control "public, max-age=604800"; - 禁止缓存(如 API 接口):
expires -1; add_header Cache-Control "no-cache, no-store, must-revalidate"; - 可缓存但需校验(如 HTML):
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显式声明,不依赖隐式继承