http通过判断资源是否被修改来判断是否使用缓存。
涉及几个请求头参数:
ETag; // 默认是开启的。作用是开启协商缓存
if_modified_since:浏览器缓存记录的该文件的最后服务器修改时间
Cache-Control:配置缓存的细则
location / {
root "D:/work/sourcecode/nginx_html/";
index index.html;
try_files $uri $uri/ /index.html;
// 开启协商缓存
etag on;
// exact:文件修改的时间和缓存存储的时间要完全符合,还有其他属性,如before等。
if_modified_since exact ;
// 增加缓存控制。no-cache:每次请求前都对资源进行验证是否过期。must-revalidate:可缓存但必须再向源服务器进行确认
add_header Cache-Control "no-cache,must-revalidate";
}
上面的方法会将全部的资源都会进行缓存,但是在新版本上线时又希望用户能及时看到最新的内容。这种情况下上面的缓存方法就不太适用了,用户体验也不好。
我们可以将静态页面比如html或者根目录进行协商缓存,根目录下面的js、css、图片这种进行强缓存。
#子系统目录
location /sub1/ {
root "D:/work/sourcecode/nginx_html/159/";
index index.html;
try_files $uri $uri/ /sub1/index.html;
#协商缓存
add_header Cache-Control "no-cache,must-revalidate";
}
# 单独为 CSS、js 提供缓存策略(放在 server 块内,与主 location 并列)
location ~ ^/sub1/.+\.(css|js)$ {
root "D:/work/sourcecode/nginx_html/159/";
#强缓存,36000000秒后过期
add_header Cache-Control "public,max-age=36000000";
}