网站制作学习网经验与学习→正文:nginx 配置cache 做CDN
字体:

nginx 配置cache 做CDN

经验与学习 2023/6/29 15:39:42  点击:不统计

原载于:转www.载for网站制作学习asp必.cn究

nginx做cnd服务配置proxy_cache 整个过程
 
1. 首先配置缓存位置 和缓存空间大小。 在nginx 配置下,跟站点服务配置 server 同级别。
proxy_temp_path # 临时缓存保存位置 
proxy_cache_path: cache 内容保存位置
proxy_temp_path /data/proxy_temp_path
proxy_cache_path /data/proxy_cache_path levels=1:2 keys_zone=cache_one:500m inactive=1d max_size=15g;
详细解释: 
 /data/proxy_cache_path  缓存磁盘本地保存路径
 levels指定缓存的目录结构,默认为级别为1:2,代表缓存目录下第一级的目录个数不能超过1个,第二级的目录个数不能超过2个,最大为3个比如 1:2:3。而数字表示文件夹名称位数,比如2 则文件夹名称为,ab bc 等
 keys_zone定义在内存中用于存储缓存key和相关数据的区域,使用时应指定合适的大小
 max_size = 15g  本地缓存最大15G
 
 
2. 在sever 配置upstream ,没有内容或者失效的时候,回源取内容,定义回源服务器 与server 同级别
upstream forasp {
        server 172.22.22.211:80; # 如果有多个 可以在端口 后面添加 weight=6; 权重,nginx 根据权重自动分配服务器
}
upstream forasp_ssl {
        server 172.22.22.211:443;
}
server 可以走内网(如果有会更快),也可以直接走外网ip
 
 
3. 配置 server 接受服务
(1) 配置proxy代理回源,在80端口server 中配置,当然也可以通过 location指向不同的upstream
location / {
proxy_pass http://forasp;
}
如果是 443 ssl 则要配置:
location / {
proxy_pass https://forasp_ssl;
}
意思是端口要与上面的 upstream对应上
 
 (2) 开始定义cache 的索引cache 以及保存配置, 以443端口为例,80 的除了upstream不一样其他一样
location / {
proxy_cache cache_one; # 缓存区 ,参考 上面1 对应的 keys_zone 的名字
proxy_cache_key "$host$server_port$request_uri"; # 用什么作为缓存的key ,一般是url/uri 有的用 $scheme ,这里用端口$server_port代替了
proxy_cache_valid  200 304 20m;# 缓存条件 upstream 是200 或者304 缓存时间20分钟。 也可以设置为 1d 1天 2h 2小时 
proxy_ignore_headers Set-Cookie; # 这里是定义忽略cookie header到后端。如果是动态网页,或者php 没有这个配置,就会一直miss
proxy_cache_methods GET POST; # 缓存的方法,如果要有其他方法不缓存
add_header X-Cache $upstream_cache_status; #将缓存是否命中的结果返回
proxy_pass https://forasp_ssl;
}
(3) 如果区分 PC端还是移动端cache ,则需要在key 加上对应的条件,然后将 $ismobile 加到 proxy_cache_key 里面,结果如下:
set $ismobile 0;
if ( $http_user_agent ~* "(Android|iPhone|Windows Phone|UC|Kindle)" ){ 
       set $ismobile 1;
}
location / {
proxy_cache cache_one; # 缓存区 ,参考 上面1 对应的 keys_zone 的名字
proxy_cache_key $ismobile$host$server_port$request_uri; # 用什么作为缓存的key ,一般是url/uri 有的用 $scheme ,这里用端口$server_port代替了
proxy_cache_valid  200 304 20m;# 缓存条件 upstream 是200 或者304 缓存时间20分钟。 也可以设置为 1d 1天
proxy_ignore_headers Set-Cookie; # 这里是定义忽略cookie header到后端。如果是动态网页,或者php 没有这个配置,就会一直miss
proxy_cache_methods GET; # 缓存的方法,如果要有其他方法不缓存
add_header X-Cache $upstream_cache_status; #将缓存是否命中的结果返回
proxy_pass https://forasp_ssl;
}
4. 查看nginx 作为cdn 效果
访问一个页面,或者js,在浏览器中查看响应标头 
X-Cache: HIT; 表示命中缓存
X-Cache: MISS; 表示没有缓存,首次加载/或者缓存失效等。
 

原载于:网f站o学a习s制p作.cn

·上一篇:nginx cache缓存php 伪静态 >>    ·下一篇:nginx配置判断是PC还是移动端 >>
推荐文章
最新文章