下载模块
1 |
wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz |
安装
1 2 3 4 5 6 7 |
tar -zxvf ngx_cache_purge-2.3.tar.gz #进入nginx源码目录 ./configure --prefix=CUSTOM_DIR --with-http_ssl_module --add-module=./ngx_cache_purge-2.3 #此处的模块目录为你解压的文件夹所在目录,此处要注意的是,如果之前有开启其他模块,例如我之前开启了ssl,在增加模块时,需要带上之前的模块`--with-http_ssl_module` make #备份之前的nginx文件之后 cp objs/nginx CUSTOM_DIR/sbin/ #重启nginx后即完成安装 |
配置
nginx.conf中增加如下配置
1 2 3 4 5 6 7 8 |
# 两个path需提前创建,否则nginx启动失败, fastcgi_cache_path /dev/shm/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=1d max_size=300M; fastcgi_temp_path /dev/shm; fastcgi_cache_key "$scheme$request_method$host$request_uri"; fastcgi_cache_use_stale error timeout invalid_header http_500; # 忽略一切nocache申明,避免不缓存伪静态等 fastcgi_ignore_headers Cache-Control Expires Set-Cookie; # end |
修改server段配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#······以上略······ set $skip_cache 0; # post访问不缓存 if ($request_method = POST) { set $skip_cache 1; } # 动态查询不缓存 if ($query_string != "") { set $skip_cache 1; } if ($query_string ~* "joke_image"){ set $skip_cache 1; } # 后台等特定页面不缓存 if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") { set $skip_cache 1; } location ~ .+\.php($|/) { # ······此处略······ # 新增ngx_cache_purge缓存规则 fastcgi_cache_bypass $skip_cache; fastcgi_no_cache $skip_cache; add_header X-Cache "$upstream_cache_status From $host"; fastcgi_cache WORDPRESS; fastcgi_cache_valid 200 301 302 1d; } #······以下略······ |
至此ngxcachepurge模块的安装配置已经完成
清除缓存,有两种方式,一种是安装插件Nginx Helper,另一种简单粗暴,直接在缓存目录 /dev/shm/nginx-cache清除文件。
缓存效果
替换新的配置,并且重载Nginx之后,访问前台页面,查看header,会多出一个X-Cache 标志。
X-Cache 一般会有3个状态:MISS、HIT、BYPASS。
MISS表示未命中
即这个页面还没被缓存,新发布或刚被删除的页面,首次访问将出现这个状态(图略)。
HIT表示缓存命中
打开一个会缓存的页面,比如文章内容html页面,F5刷新几次即可在F12开发者模式当中的Header头部信息中看到如图缓存命中状态:
Nginx开启fastcgi_cache缓存加速,支持html伪静态页面
BYPASS表示缓存黑名单
即页面路径在Nginx规则中被设置成不缓存(set $skipcache 1;),比如WP后台,查看header:
Nginx开启fastcgicache缓存加速,支持html伪静态页面
如果你发现想要缓存的页面却是这个状态,就可以去检查排除规则中是不是包含了这个路径!反之,如果你发现后台登录不了,或者各种登陆态丢失问题,则应该到排除规则中加上该页面路径的关键字。