外观
3.2 缓存规则配置
约 441 字
缓存配置
本页对应「三、操作步骤」的 3.2,完成缓存规则配置。返回上级:静态资源与缓存配置说明。
前置条件
- 3.1 已完成,current 软链可用且站点可正常返回 200。
- 资源文件名带内容指纹,index.html 为入口文件。
- 已备份站点配置文件。
操作步骤
- 备份站点配置。
sudo cp /etc/nginx/sites-available/example.com.conf /root/example.com.conf.bak- 按资源类型设置缓存头,在 server 块中加入:
location ~* \.(?:js|css|woff2|png|jpg|svg)$ {
expires 1y;
add_header Cache-Control "public, max-age=31536000, immutable";
access_log off;
try_files $uri =404;
}
location = /index.html {
add_header Cache-Control "no-cache, must-revalidate";
etag on;
}
location / {
try_files $uri $uri/ /index.html;
}- 启用压缩,降低传输体积。
gzip on;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_vary on;
gzip_types text/css application/javascript application/json image/svg+xml;- 校验并平滑重载。
sudo nginx -t
sudo systemctl reload nginx- 检查实际响应头,确认规则命中。
curl -sSI https://example.com/assets/app.3f2a1c.js | grep -i -E 'cache-control|expires|etag|content-encoding'
curl -sSI https://example.com/index.html | grep -i -E 'cache-control|etag'结果确认
- 带指纹资源返回
max-age=31536000, immutable,且文本类资源带Content-Encoding: gzip。 - index.html 返回
no-cache并带 ETag,二次请求可能返回 304。 - 未匹配后缀的文件走
location /,不会被误命中长缓存。 nginx -t无 warning,重新加载后错误日志无新增。
注意事项
- location 的匹配顺序影响结果,正则 location 会覆盖前缀匹配,写入位置要先确认。
expires与手写Cache-Control同时存在时后者生效,不要重复配置造成歧义。- 开启 gzip 后不要对 jpg、png、woff2 等已压缩格式重复压缩。
- 修改缓存策略后需要刷新 CDN 侧规则,否则边缘仍按旧策略缓存。