WP_使用_FastCGI_Cache_实现高效页面缓存

来源:互联网 发布:淘宝名字叫什么好 编辑:程序博客网 时间:2024/06/05 20:21
前言 
 
 
页面缓存(Page Cache)是 WordPress 性能优化比较重要的一环,目前 WP 有很多页面缓存插件:W3 Total Cache、WP Super Cache、Comet Cache 等,不过它们都是 务器软件 —— PHP —— WP缓存插件 —— 本地或对象缓存,差不多要经过四个阶段,在高并发下效率是很低的。 
 
 
而目前比较流行的就是 服务软件 —— FastCGI Cache 或者 服务器软件 —— SRcache 拓展 —— 对象缓存,跳过 PHP 以提高效率。 后者的教程:《用 Nginx+Redis Cache 给 WordPress 提速》 
 
 
从效率上讲两个方式是没有差别的,这篇文章 也证明了这一点,不过我认为连接 Redis,有需要经过 TCP/IP 并且 Redis 的执行也有一定损益,所以我更中意于前者。 
 
原理 
 
 
Nginx 内置 FastCGI 缓存,讲缓存结果置放到 tmpfs 内存中去,就可以极大的提高效率和处理时间。不过 FastCGI 缓存不能动清除缓存,当文章需要变动或者产生新评论时就会尴尬了,因此还需要搭配 ngx_cache_purge 拓展,搭配 Nginx Helper 插件以避免前面所说的尴尬。 
 
教程 
 
 
 
安装 Nginx ngx_cache_purge 模块 
 
复制代码
  1. #下载 ngx_cache_purge
  2. git clone https://github.com/FRiCKLE/ngx_cache_purge.git

  3. #重新编译 Nginx
  4. ./configure ···你的参数···  .   --add-module=/path/to/ngx_cache_purge-2.3
 
 
ramdisk 
 
 
将 FastCGI_cache 内容 放置在 /var/run 中挂载为 ramdisk,当然了如果网站内容很多,那么内存也一定要大。 
一般来说,/var/run 的大小是总内存的 20%,例如一个 4G 内存的机器,可用容量为 794 M 
引用
root@mf8.biz:~# free -m 
             total       used       free     shared    buffers     cached 
Mem:          3965       1443       2521        100        160        687 
-/+ buffers/cache:        595       3370 
Swap:            0          0          0 
 
root@mf8.biz:~# df -h /var/run 
Filesystem      Size  Used Avail Use% Mounted on 
tmpfs           794M  352K  793M   1% /run
 
 
 
修改 Nginx 虚拟主机配置 
 
 
一、在 server{} 前添加: 
复制代码
  1. fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m;
  2. fastcgi_cache_key "$scheme$request_method$host$request_uri";
  3. fastcgi_cache_use_stale error timeout invalid_header http_500;
  4. fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
 
 
二、然后在 server{} 内添加: 
复制代码
  1. set $skip_cache 0;
  2. if ($request_method = POST) {
  3.     set $skip_cache 1;
  4.     }
  5. if ($query_string != "") {
  6.     set $skip_cache 1;
  7.     }
  8. if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") {
  9.     set $skip_cache 1;
  10.     }
  11. if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
  12.     set $skip_cache 1;
  13.     }
  14.     
  15. location ~ /purge(/.*) {
  16.     allow 127.0.0.1;
  17.     deny all;
  18.     fastcgi_cache_purge WORDPRESS "$scheme$request_method$host$1";
  19.     }
 
 
 
三、在 location ~ [^/]\.php(/|$) { 段中添加: 
复制代码
  1. fastcgi_cache_bypass $skip_cache;
  2. fastcgi_no_cache $skip_cache;
  3. fastcgi_cache WORDPRESS;
  4. fastcgi_cache_valid  60m;
 
 
 
 
 
WP设置  
 
一、在 wp-config.php 中添加:
复制代码
  1. define( 'RT_WP_NGINX_HELPER_CACHE_PATH','/var/cache/nginx-cache');
 
 
二、安装 Nginx Helper 插件 
三、按下图设置,其他默认即可: 
 
 

原文地址:http://click.aliyun.com/m/20517/

0 0