静态资源带哈希文件名可以放心长缓存,而入口 HTML 必须每次校验,否则发版后用户还看旧版。
操作步骤
location ~* \.(css|js|png|jpg|svg|woff2)$ {
expires 7d;
add_header Cache-Control "public, immutable";
}
location = /index.html {
add_header Cache-Control "no-cache";
}
要点速览
- 带内容哈希的文件(如 app.a1b2.css)用 immutable,浏览器在有效期内不再询问源站。
- index.html 用 no-cache,保证每次都向源站确认是否有新版本。
- expires 与 Cache-Control 同时设时以 Cache-Control 的 max-age 为准,二者保持一致避免歧义。
缓存策略的核心矛盾:资源要长缓存,入口要短校验,分清两者就赢了一半。