多个 WordPress 站点配置 Nginx FastCGI 缓存教程

在一台服务器上运行多个 WordPress 站点时,使用 Nginx 的 FastCGI 缓存功能可以显著提高性能。通过配置统一缓存区域,不仅能减少 PHP 处理压力,还能提升整体访问速度。

1. 配置共享 FastCGI 缓存区

编辑 /etc/nginx/nginx.confhttp 区块,添加:

fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=WORDPRESS:100m inactive=60m use_temp_path=off;
fastcgi_cache_key "$scheme$request_method$host$request_uri";

2. 创建缓存目录并授权

sudo mkdir -p /var/cache/nginx/fastcgi
sudo chown -R www-data:www-data /var/cache/nginx/fastcgi

3. 修改每个站点配置

以下是 两个 WordPress 站点的完整配置示例:

站点一:xyz.com

server {
    listen 80;
    server_name xyz.com;
    root /var/www/html/xyz.com;

    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        # 缓存控制
        set $no_cache 0;
        if ($http_cookie ~* "wordpress_logged_in_") {
            set $no_cache 1;
        }

        fastcgi_cache WORDPRESS;
        fastcgi_cache_valid 200 301 302 60m;
        fastcgi_cache_use_stale error timeout invalid_header updating;
        fastcgi_cache_bypass $no_cache;
        fastcgi_no_cache $no_cache;
        add_header X-FastCGI-Cache $upstream_cache_status;
    }
}

站点二:abc.com

server {
    listen 80;
    server_name abc.com;
    root /var/www/html/abc.com;

    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        # 缓存控制
        set $no_cache 0;
        if ($http_cookie ~* "wordpress_logged_in_") {
            set $no_cache 1;
        }

        fastcgi_cache WORDPRESS;
        fastcgi_cache_valid 200 301 302 60m;
        fastcgi_cache_use_stale error timeout invalid_header updating;
        fastcgi_cache_bypass $no_cache;
        fastcgi_no_cache $no_cache;
        add_header X-FastCGI-Cache $upstream_cache_status;
    }
}

4. 重启 Nginx 使配置生效

sudo nginx -t
sudo systemctl reload nginx

5. 验证缓存是否工作

你可以用浏览器开发者工具或 curl -I 命令检查响应头:

X-FastCGI-Cache: HIT   # 表示命中缓存
X-FastCGI-Cache: MISS  # 表示未命中

6. 缓存原理浅析

Nginx FastCGI 缓存工作机制如下:

  • 首次请求:Nginx 将请求转发给 PHP-FPM,返回结果写入磁盘缓存,并返回用户
  • 后续请求:如果 URL + 方法相同,Nginx 直接从缓存返回,不经过 PHP
  • 若检测到登录 Cookie,如 wordpress_logged_in_,Nginx 会跳过缓存
  • 缓存文件保存在 /var/cache/nginx/fastcgi 目录,以二级目录结构保存
  • 缓存有效期由 fastcgi_cache_valid 控制,可按状态码设置不同时间

这种缓存属于“响应缓存”,即整个 HTML 页面缓存,适用于匿名用户访问量大的 WordPress 站点。

结语

通过配置共享的 FastCGI 缓存区,你可以在一台服务器上高效运行多个 WordPress 站点,提升访问速度,节省资源,尤其适合中小型网站集群部署。

发表回复