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";   
}
相关推荐
寻星探路17 小时前
【Python 全栈测开之路】Python 基础语法精讲(一):常量、变量与运算符
java·开发语言·c++·python·http·ai·c#
栗子叶17 小时前
网页接收服务端消息的几种方式
前端·websocket·http·通信
梭七y17 小时前
【力扣hot100题】(133)LRU缓存
leetcode·缓存·哈希算法
xiaolyuh12319 小时前
Caffeine 缓存详解
缓存
五阿哥永琪19 小时前
Spring Data Redis 实战避坑指南:从配置到缓存预热的全链路最佳实践
redis·spring·缓存
Filotimo_19 小时前
桥接服务概念
网络协议·网络安全·信息与通信
镜中人★19 小时前
408计算机网络考纲知识点(更新中)
网络·网络协议·计算机网络
win x20 小时前
Redis 哨兵模式
数据库·redis·缓存
禾叙_21 小时前
【netty】Netty之TCP链接
网络·网络协议·tcp/ip
半路_出家ren21 小时前
17.python爬虫基础,基于正则表达式的爬虫,基于BeautifulSoup的爬虫
网络·爬虫·python·网络协议·正则表达式·网络爬虫·beautifulsoup