Nginx 客户端缓存控制

客户端缓存由 Expires 与 Cache-Control 共同决定。根据内容是否带哈希设置缓存时间,比统一长期缓存更安全。

推荐组合

location / {
    expires -1;
    try_files $uri $uri/ /index.html;
}

location ~* \.(?:png|jpg|jpeg|gif|webp|svg|woff2)$ {
    expires 7d;
    access_log off;
    try_files $uri =404;
}

location /static/hash/ {
    expires 1y;
    add_header Cache-Control "public, immutable";
    try_files $uri =404;
}

常用时间

内容建议
HTMLno-cache 或很短时间
普通图片/字体数小时到数天
带哈希 CSS/JS1 年 + immutable
私有响应由应用返回 private/no-store,不在此长期缓存

验证

curl -I http://127.0.0.1/
curl -I http://127.0.0.1/static/hash/app.a1b2.js