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";   
}
相关推荐
你我约定有三3 小时前
MyBatis--缓存详解
spring boot·缓存·mybatis
天涯海风5 小时前
检索增强生成(RAG) 缓存增强生成(CAG) 生成中检索(RICHES) 知识库增强语言模型(KBLAM)
人工智能·缓存·语言模型
m0_595199858 小时前
Redis(以Django为例,含具体操作步骤)
数据库·redis·缓存
rainFFrain12 小时前
Boost搜索引擎项目(详细思路版)
网络·c++·http·搜索引擎
.Shu.13 小时前
计算机网络 HTTPS 全流程
网络协议·计算机网络·https
还听珊瑚海吗17 小时前
基于WebSocket和SpringBoot聊天项目ChatterBox测试报告
spring boot·websocket·网络协议
huisheng_qaq19 小时前
【ElasticSearch实用篇-03】QueryDsl高阶用法以及缓存机制
elasticsearch·缓存·nosql·querydsl·score打分机制
猿究院--冯磊20 小时前
计算机网络--HTTP协议
网络协议·计算机网络·http
元清加油21 小时前
【Goland】:协程和通道
服务器·开发语言·后端·网络协议·golang
让代码飞~1 天前
idea进阶技能掌握, 使用自带HTTP测试工具,完全可替代PostMan
java·http·intellij-idea·postman