nginx缓存功能的设置
来源:互联网 发布:淘宝自助开通账户在哪 编辑:程序博客网 时间:2024/06/03 02:02
这几天要用到nginx的缓存,折腾了两天,终于搞定了,
把方法写下来以示备忘或给后来者一个参考:
首先用的缓存是proxy_cache.
在http段里加入下列几句:
proxy_connect_timeout 5; proxy_read_timeout 60; proxy_send_timeout 5; proxy_buffer_size 16k; proxy_buffers 4 64k; proxy_busy_buffers_size 128k; proxy_temp_file_write_size 128k; proxy_temp_path /home/temp_dir; proxy_cache_path /home/cache levels=1:2 keys_zone=cache_one:50m inactive=20m max_size=30g;
上面的各行的参数我再时不解释,网上有很多。
接下来在要缓存的service里加入:
location /gou/detail-id-116 { ##缓存 index index.html index.htm index.php; proxy_cache cache_one; proxy_cache_valid 200 302 1h; proxy_cache_key $host$uri$is_args$args; proxy_pass http://contactpool; proxy_ignore_headers "Cache-Control" "Expires" "Set-Cookie";#不处理后端服务器返回的指定响应头 expires 30d; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }
当然可以用正则缓存更多的页面如:~.*\.(php|jsp|cgi)?$
上面的我只解释一下地方:proxy_ignore_headers这个表示不处理后端服务器返回的指定响应头,作用就是能够缓存动态页面,比如.php的页面,如果不加这一行就只能缓存静态的页面内容了。
现在:nginx -s reload 后缓存就有了,
接下来如何在需要的时候清理缓存呢,
网上一位大牛分析了nginx是如何存的缓存文件:
计算方法:
1) nginx先把请求地址/1.png用md5进行哈希,得到e0bd86606797639426a92306b1b98ad9
md5的参数就是上面的配置中:
proxy_cache_key值,如md5("www.xxx.com/gou/detail-id-116");
2) level=1:2就是把最后一位数9拿出来建一个目录,然后再把9前面的2位建一个目录,最后把刚才得到的这个缓存文件放到9/ad目录中。
同样的方法推理,如果level=1:1,那么缓存文件的路径就是/usr/local/nginx/cache/9/d/e0bd86606797639426a92306b1b98ad9
那么我们就可以写一个脚本来清理特定的缓存了:
#!/usr/bin/env php<?php$cache_dir = '/usr/local/nginx/cache/';$request_uri = $argv[1];$url_hash = md5($request_uri);$dir1 = substr($url_hash,-1,1) . '/';$dir2 = substr($url_hash,-3,2) . '/';$cached_file = $cache_dir . $dir1 . $dir2 . $url_hash;if (is_file($cached_file)) { if (unlink($cache_dir . $dir1 . $dir2 . $url_hash)) { echo $request_uri . " 缓存清除成功\n"; } else { echo $request_uri . " 缓存清除失败\n"; }} else { echo $request_uri . " 未被缓存\n";}
各项注释晚上我回家后有时间再写,见谅!
1 0
- nginx缓存功能的设置
- nginx的缓存设置
- Nginx的proxy_cache缓存功能
- nginx的内置缓存功能
- 使用Nginx的proxy_cache缓存功能
- nginx的反向代理及缓存功能。
- nginx缓存功能演示
- Nginx的浏览器本地缓存设置
- nginx静态资源设置缓存的方法
- Nginx:设置Nginx作为缓存
- nginx的缓存设置 expires缓存提升网站负载
- nginx缓存设置
- nginx缓存设置
- nginx缓存设置
- nginx缓存设置
- nginx 设置缓存
- Nginx HTTP缓存设置
- nginx缓存设置proxy_cache
- 也不是谁的错 谎言再多 其余你还爱我
- 世界顶级图表-华尔街日报配色方案详解
- 你许我地老天荒,却为她穿上婚纱!
- 设计模式-六大原则
- 灰太狼与光头强
- nginx缓存功能的设置
- 疯狂android讲义目录
- 【Linux】Linux文件查找命令find,xargs详述
- 游戏云间之二-网络环境问题
- 事务管理器
- iOS基础一 NSNumber
- 设计模式自我理解_java篇
- VMWare 虚拟机系统 ping 不通主机解决方案
- Ubuntu jdk 1.7 安装