缓存配置优化
合理的缓存策略可大幅减少服务器负载、降低带宽消耗并提升用户体验。NGINX 通过 expires 和 add_header 指令控制缓存行为。
基础缓存控制
expires 指令
nginx
location /static/ {
root /var/www/html;
expires 30d;
add_header Cache-Control "public, no-transform";
}
expires 30d— 设置Cache-Control: max-age=2592000和Expires头expires -1— 禁止缓存expires epoch— 设置为过期时间 1970-01-01expires off— 不修改缓存头
按文件类型设置缓存
不同类型不同策略
nginx
server {
# 静态资源 - 长期缓存
location ~* \.(css|js|jpg|jpeg|png|gif|svg|ico|woff|woff2|ttf)$ {
expires 365d;
add_header Cache-Control "public, immutable";
}
# HTML - 短期缓存
location ~* \.html$ {
expires 1h;
add_header Cache-Control "public, no-cache";
}
# 动态 API - 不缓存
location /api/ {
expires -1;
add_header Cache-Control "no-store, no-cache, must-revalidate";
}
}
immutable告诉浏览器在有效期内文件不会变化,刷新页面也不重新验证。适用于文件名带 hash 的构建产物。
条件缓存
按文件命名模式
nginx
location /assets/ {
# 带 hash 的文件名长期缓存
location ~* \.[a-f0-9]{8,}\.(css|js)$ {
expires 365d;
add_header Cache-Control "public, immutable";
}
# 普通文件短期缓存
expires 7d;
add_header Cache-Control "public";
}
缓存控制头说明
Cache-Control 指令
public— 可被任何缓存存储private— 仅浏览器可缓存no-cache— 每次使用需验证 freshnessno-store— 不存储任何缓存must-revalidate— 过期后必须验证max-age=3600— 有效缓存时间(秒)s-maxage=3600— CDN/代理缓存时间immutable— 有效期内不重新验证
代理缓存控制
控制后端缓存行为
nginx
location /api/ {
proxy_pass http://backend;
# 忽略后端设置的缓存头
proxy_ignore_headers Cache-Control;
proxy_ignore_headers Expires;
proxy_ignore_headers Set-Cookie;
# 在 NGINX 层强制缓存
proxy_cache_valid 200 10m;
}
当后端缓存头不合理时,
proxy_ignore_headers可覆盖。注意Set-Cookie响应不应被缓存。
ETag 和 Last-Modified
协商缓存配合
nginx
location /static/ {
etag on; # NGINX 默认开启
# 自动基于文件大小和修改时间生成 ETag
expires 1d;
add_header Cache-Control "public, no-cache";
}
no-cache配合 ETag 实现协商缓存:每次都验证但未过期直接 304- 不设置过期时间时浏览器可能无限期缓存
要点总结
- 静态资源(CSS/JS/图片)设置 30-365 天长期缓存
- 带 hash 文件名的构建产物使用
immutable指令 - HTML 使用短期缓存(1 小时),确保内容更新及时
- API 响应设置
no-store禁止缓存 Cache-Control优先级高于Expires头- 协商缓存(ETag/Last-Modified)适合需要实时性但可复用的内容
📝 发现内容有误?点击此处直接编辑