WP 使用 FastCGI Cache 实现高效页面缓存
本文最后更新于 2595 天前,其中的信息可能已经有所发展或是发生改变。

前言

页面缓存(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 模块

#下载 ngx_cache_purge
git clone https://github.com/FRiCKLE/ngx_cache_purge.git

#重新编译 Nginx
./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{} 前添加:

fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

二、然后在 server{} 内添加:

set $skip_cache 0;
if ($request_method = POST) {
    set $skip_cache 1;
    }
if ($query_string != "") {
    set $skip_cache 1;
    }
if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") {
    set $skip_cache 1;
    }
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
    set $skip_cache 1;
    }
    
location ~ /purge(/.*) {
    allow 127.0.0.1;
    deny all;
    fastcgi_cache_purge WORDPRESS "$scheme$request_method$host$1";
    }

三、在 location ~ [^/]\.php(/|$) { 段中添加:

fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
fastcgi_cache WORDPRESS;
fastcgi_cache_valid  60m;

WP设置

一、在 wp-config.php 中添加:

define( 'RT_WP_NGINX_HELPER_CACHE_PATH','/var/cache/nginx-cache');

二、安装 Nginx Helper 插件

三、按下图设置,其他默认即可:

参考文章

https://easyengine.io/wordpress-nginx/tutorials/single-site/fastcgi-cache-with-purging/

https://centminmod.com/nginx_configure_wordpress.html

https://blog.linuxeye.cn/439.html

评论

  1. 7年前
    2017-3-07 17:55:34

    膜拜博主

    • 妙正灰
      博主
      徒步旅行
      7年前
      2017-3-07 22:11:42

      谈不上,谈不上

本文评论已关闭
上一篇
下一篇