nginx实现http的缓存协商缓存

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";   
}
相关推荐
moonless02222 天前
FastAPI框架,这一小篇就能搞懂精髓。
http·fastapi
-Xie-3 天前
Mysql杂志(十六)——缓存池
数据库·mysql·缓存
七夜zippoe3 天前
缓存与数据库一致性实战手册:从故障修复到架构演进
数据库·缓存·架构
weixin_456904273 天前
跨域(CORS)和缓存中间件(Redis)深度解析
redis·缓存·中间件
FPGA_Linuxer3 天前
FPGA 40 DAC线缆和光模块带光纤实现40G UDP差异
网络协议·fpga开发·udp
real 13 天前
传输层协议UDP
网络·网络协议·udp
ftpeak3 天前
从零开始使用 axum-server 构建 HTTP/HTTPS 服务
网络·http·https·rust·web·web app
MarkHard1233 天前
如何利用redis使用一个滑动窗口限流
数据库·redis·缓存
hsjkdhs3 天前
网络编程之UDP广播与粘包问题
网络·网络协议·udp
心想事成的幸运大王3 天前
Redis的过期策略
数据库·redis·缓存