速度优化对建站是重要的,速度慢会损失许多流量。在 WordPress 优化方面,一般有两个方向,一个是优化程序 Runtime,一个则是静态文件,程序 Runtime 方面我用的是 Redis 对象加速,而在静态页面方面,则需要用到 Nginx 的 FastCGI Cache 。原理方面有空另将,我们把重点放在步骤上。(本文基于军哥 LNMP 环境)
FastCGI 全局配置
首先需要添加 FastCGI 的全局配置,定义缓存池名称和大小,这些设定要添加在 Nginx 的 http block 里面(在 Server Block 以外),修改的文件是 /usr/local/nginx/conf/nginx.conf:
fastcgi_cache_path /mu/cache levels=1:2 keys_zone=wpmu:1024m inactive=1d max_size=5G; 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; add_header Fastcgi-Cache $upstream_cache_status;
这里定义的缓存路径是 /mu/cache ,不少人为了追求极致速度,这个目录会设置在 /var/run 。keys_zone 参数里面 wpmu 是缓存池名称,1024m 则是缓存池大小(指的是 in-memory cache,单位是 Megabytes),inactive 则是缓存过期时间(单位是 Days,即一天),max_size 指的是硬盘缓存大小。
站点配置
全局配置结束之后,则需要对希望开启 FastCGI 缓存的站点进行单独配置,在配置文件中加入:
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; }
新增并在站点配置文件中讲 enable-php.conf 改为 enable-php-cache.conf:
location ~ [^/]\.php(/|$) { try_files $uri =404; fastcgi_pass unix:/tmp/php-cgi.sock; fastcgi_index index.php; include fastcgi.conf; fastcgi_cache_bypass $skip_cache; fastcgi_no_cache $skip_cache; add_header X-Cache "$upstream_cache_status From $host"; fastcgi_cache wpmu; fastcgi_cache_valid 200 301 302 304 1d; } location ~ /purge(/.*) { allow 127.0.0.1; deny all; fastcgi_cache_purge wpmu "$scheme$request_method$host$1"; }
重启 lnmp:
lnmp restart
安装 Nginx Helper 插件
在 WordPress Mu 中安装 Nginx Help 插件,在整个网络(站群)中启用,并且按照下面这个配置:
验证缓存状态
要怎么知道缓存是否生效呢?首先访问一下网站,然后在 Terminal 用 Curl 命令再次访问站点,如果返回头(Resepnse Header)显示「HIT」则意味着缓存生效。
❯ curl -I https://uncle.ws HTTP/2 200 server: nginx date: Thu, 13 Oct 2022 12:22:08 GMT content-type: text/html; charset=UTF-8 vary: Accept-Encoding link: <https://uncle.ws/wp-json/>; rel="https://api.w.org/" x-cache: HIT From uncle.ws
文章评论