操作环境

  • 硬件:华为云服务器
  • 操作系统:Rocky Linux 9.0 64bit
  • 服务器软件:nginx 1.24.0,php 8.2.6,openssl 3.0.7,MySQL 8.0.33,WordPress6.2.2

前提条件

  • nginx已安装,SSL已开启。
  • php已安装。
  • MySQL已安装。
  • WordPress已经安装,并运行正常。
  • 已安装git工具。(未安装的用 yum install -y git 安装)

相关知识

1.fastcgi cache 的运行机制

fastcgi cache 的运行机制是将后端 CGI 服务返回的页面缓存起来,后续请求到来时直接返回页面,省去与后端服务通信及生成页面的消耗。fastcgi cache 与squid、varnish、CDN 等原理类似,由于减少了后端请求,原则上性能会比WordPress 的各种缓存插件(如:WP Super Cache、W3 Total Cache、WP Rocket等)高出许多。

2.proxy_cache与fastcgi_cache对比

proxy_cache的作用是缓存后端服务器的内容,可能是任何内容,包括静态的和动态。
fastcgi_cache的作用是缓存fastcgi生成的内容,很多情况是php生成的动态的内容。
proxy_cache缓存减少了nginx与后端通信的次数,节省了传输时间和后端宽带。
fastcgi_cache缓存减少了nginx与php的通信的次数,更减轻了php和数据库(mysql)的压力,这比用memcached之类的缓存要轻松得多。

3.开源版nginx的限制和解决方案

Nginx 内置 FastCGI 缓存,将缓存结果置放到 tmpfs 内存中去,就可以极大的提高效率和处理时间。不过开源版nginx的 FastCGI 缓存不能自动清除缓存,当文章需要变动或者产生新评论时就会尴尬了,因此还需要搭配第三方ngx_cache_purge 拓展,搭配 Nginx Helper 插件以避免前面所说的尴尬。

本文将详细介绍如何下载安装 ngx_cache_purge拓展模块,并开启 fastcgi cache服务。

操作步骤

一、下载安装ngx_cache_purge拓展模块

1.下载第三方模块ngx_cache_purge

cd /usr/local/src
git clone https://github.com/FRiCKLE/ngx_cache_purge.git

上述指令运行完毕,会在当前目录下新建 ngx_cache_purge目录,目录里面是新下载的模块。

也可使用以下指令下载ngx_cache_purge模块,并解压,效果一样,只是解压出来的目录为 ngx_cache_purge-2.3,在后面的 configure指令中注意对应修改,或者将目录改名。

wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz
tar zxvf ngx_cache_purge-2.3.tar.gz

2.查看nginx编译参数

具体指令:

  • cd /usr/local/nginx/sbin
  • ./nginx -V
[2023-06-02 01:22:39]  [root@hecs-288529 src]# cd /usr/local/nginx/sbin
[2023-06-02 01:22:45]  [root@hecs-288529 sbin]# ./nginx -V
[2023-06-02 01:22:45]  
nginx version: nginx/1.24.0
[2023-06-02 01:22:45]  built by gcc 11.3.1 20221121 (Red Hat 11.3.1-4) (GCC) 
[2023-06-02 01:22:45]  built with OpenSSL 3.0.7 1 Nov 2022
[2023-06-02 01:22:45]  TLS SNI support enabled
[2023-06-02 01:22:45]  configure arguments: --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module --with-http_v2_module --user=nginx --group=nginx

请记住指令输出的 configure arguments,后面重新配置编译参数时要用。

3.重新配置nginx编译参数

进入nginx的源代码目录,并使用 configure指令重新配置编译参数。

具体是在上一步指令输出编译参数的基础上,增加 --add-module=/usr/local/src/ngx_cache_purge参数。注意参数中的路径(目录)要与第一步中的一致。

cd /usr/local/src/nginx-1.24.0
./configure  --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module --with-http_v2_module  --add-module=/usr/local/src/ngx_cache_purge  --user=nginx --group=nginx

4.重新编译nginx软件,但不要安装

make

5.备份原来的文件

mv /usr/local/nginx/sbin/nginx{,_date +%F}

6.拷贝新编译的文件到安装目录

cp objs/nginx /usr/local/nginx/sbin/nginx

7.检查配置

 /usr/local/nginx/sbin/nginx -t

8. 完成升级

make upgrade

9.检查是否安装成功

./nginx -V 2>&1 | grep -o ngx_cache_purge

以下内容为上述第7-9步的指令输出:

[root@hecs-288529 nginx-1.24.0]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@hecs-288529 nginx-1.24.0]# make upgrade
/usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
kill -USR2 cat /usr/local/nginx/logs/nginx.pid
sleep 1
test -f /usr/local/nginx/logs/nginx.pid.oldbin
kill -QUIT cat /usr/local/nginx/logs/nginx.pid.oldbin
[root@hecs-288529 nginx-1.24.0]# cd /usr/local/nginx/sbin
[root@hecs-288529 sbin]# ./nginx -V 2>&1 | grep -o ngx_cache_purge
ngx_cache_purge

二、开启fastcgi cache

1.查看内存情况,并新建缓存目录

具体指令如下:

  • free -m
  • df -h /var/run
  • cd /var/run
  • mkdir nginx-cache

以下为指令输出内容:

[root@hecs-288529 ~]# free -m
               total        used        free      shared  buff/cache   available
Mem:            3661        1491        1244          72        1235        2170
Swap:              0           0           0
[root@hecs-288529 ~]# df -h /var/run
Filesystem      Size  Used Avail Use% Mounted on
tmpfs           733M   24M  709M   4% /run
[root@hecs-288529 ~]# cd /var/run
[root@hecs-288529 run]#mkdir nginx-cache

2.修改nginx.conf配置文件

2.1 在http块增加以下内容
# fastcgi_cache_path设置全局的缓存路径、文件大小等,可多次出现设置不同的缓存池
fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m max_size=500m;
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;
2.2 在https的server块增加以下内容
# 缓存策略指示变量
set $skip_cache 0;
# post访问不缓存
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";
}
2.3 在location ~ \.php$块增加以下内容
# $skip_cache参数为1时不使用缓存
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
# 添加header字段,指示缓存命中状态(调试使用)           
add_header X-Cache "$upstream_cache_status From $host";
add_header Nginx-Cache "$upstream_cache_status";
add_header Last-Modified $date_gmt;
add_header X-Frame-Options SAMEORIGIN;  # 只允许本站用 frame 来嵌套
add_header X-Content-Type-Options nosniff;  # 禁止嗅探文件类型
add_header X-XSS-Protection "1; mode=block"; # XSS 保护
# 使用的keyzone,这里使用http块中定义的WORDPRESS           
fastcgi_cache WORDPRESS;
# 为指定的http返回代码指定缓存时间
fastcgi_cache_valid  200 301 302 1d;

3.重启nginx服务

用命令 systemctl restart nginx重启nginx服务,再使用命令 systemctl status nginx查看nginx服务状态。

[root@hecs-288529 nginx-cache]# systemctl restart  nginx
[2023-06-02 02:51:48]  
[root@hecs-288529 nginx-cache]# systemctl status  nginx
[2023-06-02 02:51:51]  

 nginx.service - nginx
[2023-06-02 02:51:51]       Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: disabled)
[2023-06-02 02:51:51]      Drop-In: /usr/lib/systemd/system/nginx.service.d
[2023-06-02 02:51:51]               php-fpm.conf
[2023-06-02 02:51:51]       Active: active (running) since Fri 2023-06-02 02:51:49 CST; 2s ago
[2023-06-02 02:51:51]      Process: 17124 ExecStart=/usr/local/nginx/sbin/nginx (code=exited, status=0/SUCCESS)
[2023-06-02 02:51:51]     Main PID: 17125 (nginx)
[2023-06-02 02:51:51]        Tasks: 5 (limit: 23205)
[2023-06-02 02:51:51]       Memory: 5.2M
[2023-06-02 02:51:51]          CPU: 17ms
[2023-06-02 02:51:51]       CGroup: /system.slice/nginx.service
[2023-06-02 02:51:51]               17125 "nginx: master process /usr/local/nginx/sbin/nginx"
[2023-06-02 02:51:51]               17126 "nginx: worker process"
[2023-06-02 02:51:51]               17127 "nginx: worker process"
[2023-06-02 02:51:51]               17128 "nginx: cache manager process"
[2023-06-02 02:51:51]               17129 "nginx: cache loader process"
[2023-06-02 02:51:51]  
[2023-06-02 02:51:51]  Jun 02 02:51:49 hecs-288529 systemd[1]: Starting nginx...
[2023-06-02 02:51:51]  Jun 02 02:51:49 hecs-288529 systemd[1]: Started nginx.
[2023-06-02 02:51:51]  

请注意,输出中多了两个进程的信息,说明缓存已启用:

  • 17128 “nginx: cache manager process”
  • 17129 “nginx: cache loader process”

三、测试验证缓存启用情况

1.用curl测试缓存是否启用

可以在客户端cmd窗口使用 curl -I https://wslibai.com指令测试fastcgi_cache是否启用。第一次访问时 Nginx-Cache: MISS,表示无缓存;第二次访问时 Nginx-Cache: HIT表示缓存命中。

C:\Users\Administrator>curl -I https://wslibai.com
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Fri, 02 Jun 2023 03:21:53 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
X-Powered-By: PHP/8.2.6
X-UA-Compatible: IE=edge
Link: <https://wslibai.com/wp-json/>; rel="https://api.w.org/"
Strict-Transport-Security: max-age=63072000; includeSubdomains; preload
X-Cache: MISS From wslibai.com
Nginx-Cache: MISS
Last-Modified: Friday, 02-Jun-2023 03:21:53 GMT
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block


C:\Users\Administrator>curl -I https://wslibai.com
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Fri, 02 Jun 2023 03:22:03 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
X-Powered-By: PHP/8.2.6
X-UA-Compatible: IE=edge
Link: <https://wslibai.com/wp-json/>; rel="https://api.w.org/"
Strict-Transport-Security: max-age=63072000; includeSubdomains; preload
X-Cache: HIT From wslibai.com
Nginx-Cache: HIT
Last-Modified: Friday, 02-Jun-2023 03:22:03 GMT
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block

2.查看wordpress的站点健康状态

进入wordpres的后台管理界面,通过 工具\站点健康界面查看网站的健康状态,发现fastcgi_cache启用后,服务器响应时间达到了惊人的49ms,远小于推荐的600ms临界值。

工具\站点健康界面响应时间方面的输出内容如下: 服务器响应时间的中位数是 49 毫秒,小于推荐的 600 毫秒临界值。。具体截屏如下:

3.用gtmetrix.com测试站点速度

用gtmetrix.com测试站点速度,结果 摘要为: GTmetrix Grade=ATTFB=883msFully Loaded Time=1.8s。详细情况见截图和链接。


Latest Performance Report for: https://wslibai.com/ | GTmetrix

参考资料

  1. nginx的fastcgi_cache和proxy_cache区别
  2. WP 使用 FastCGI Cache 实现高效页面缓存 – 米饭粑
  3. nginx之详解fastcgi指令 – 掘金
  4. Nginx 配置 fastcgi cache – 知乎
  5. LNMP安装ngx_cache_purge缓存清除组件 – VPS评测与排名