萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

CentOS 7/8/9 上部署 Varnish 6/7 加速 WordPress 完整實戰

Varnish Cache 是高效能 HTTP 反向代理緩存加速器,能將動態 WordPress 頁面緩存至記憶體,大幅降低 PHP-FPM/MySQL 壓力,提升響應速度 10-100 倍。本文基於 **CentOS 7/8/9 (RHEL/Rocky/AlmaLinux)**,部署 **Varnish 6.0/7.x LTS**,配合 **Nginx (SSL 終結) + PHP-FPM** 架構,實現 WordPress 全站加速,含 **後台/登入/動態頁面排除緩存**、**緩存清理**、**優化 VCL** 等生產級實踐。

架構總覽

Client (HTTPS:443)
    ↓
Nginx (SSL 終結, 靜態資源直接服務, 代理動態請求到 Varnish:8080)
    ↓
Varnish (緩存層, 端口 8080, 後端指向 PHP-FPM:9000 或 Nginx:8081)
    ↓
PHP-FPM (處理動態 PHP, Unix Socket 或 127.0.0.1:9000)
    ↓
MySQL/MariaDB

關鍵點:Nginx 處理 HTTPS、靜態文件、gzip、HTTP/2;Varnish 專注記憶體緩存動態 HTML;PHP-FPM 處理業務邏輯。三者分工明確,效能最優。

第一步:安裝 Varnish (官方倉庫獲取最新穩定版)

CentOS 7 (EOL 2024/06,建議遷移)

# 安裝 EPEL 與 Varnish 官方倉庫 (Varnish 6.0 LTS)
sudo yum install -y epel-release
sudo yum install -y https://repo.varnish-cache.org/redhat/varnish-6.0.el7.rpm
sudo yum install -y varnish

CentOS 8/9 / Rocky / AlmaLinux (Varnish 7.x LTS)

# 安裝 Varnish 官方倉庫 (自動匹配 OS 版本)
sudo dnf install -y https://repo.varnish-cache.org/redhat/varnish-7.4.el$(rpm -E %rhel).rpm
sudo dnf install -y varnish

通用啟動與開機自啟

sudo systemctl enable --now varnish
sudo systemctl status varnish  # 應顯示 active (running)

第二步:配置 Varnish 核心參數 (/etc/varnish/varnish.params)

# Varnish 監聽端口 (內部緩存端口)
VARNISH_LISTEN_PORT=8080

# 管理介面 (本地回環,安全)
VARNISH_ADMIN_LISTEN_ADDRESS=127.0.0.1
VARNISH_ADMIN_LISTEN_PORT=6082

# 緩存儲存後端: malloc (記憶體) 或 file (磁碟)
# 生產環境強烈推薦 malloc,容量設為可用記憶體 50%-70%
VARNISH_STORAGE="malloc,4G"  # 例:4GB 記憶體緩存,根據實際 RAM 調整

# 線程池參數 (高併發調優)
VARNISH_MIN_THREADS=200
VARNISH_MAX_THREADS=4000
VARNISH_THREAD_TIMEOUT=300

# 其他參數保持預設或按需調整

修改後 sudo systemctl restart varnish。

第三步:編寫生產級 WordPress VCL (/etc/varnish/default.vcl)

此 VCL 基於 Varnish 6/7 語法,核心邏輯:**緩存匿名用戶 GET/HEAD 請求的 HTML、CSS、JS、圖片等靜態資源;繞過緩存 (pass) 登入用戶、後台、POST 請求、帶 Cookie 的動態頁面**;支援 **緩存標籤 (X-Cache)**、優雅模式、後端健康檢查。

vcl 4.1;  # Varnish 6/7 使用 4.1 語法

import std;
import directors;

# 後端定義: PHP-FPM (推薦 Unix Socket 效能最佳) 或 Nginx 後端
backend php_fpm {
    .host = "127.0.0.1";  # 若用 Unix Socket,改用 .path = "/run/php-fpm/www.sock"; 並註釋 .host/.port
    .port = "9000";       # PHP-FPM 監聽端口
    .connect_timeout = 5s;
    .first_byte_timeout = 30s;
    .between_bytes_timeout = 10s;
    .probe = {
        .url = "/health_check.php";  # 需在 WordPress 根目錄建立此文件,內容: 
        .timeout = 3s;
        .interval = 10s;
        .window = 5;
        .threshold = 3;
    }
}

# 可選: 多後端負載均衡 (Director)
# director wp_cluster round-robin {
#     { .backend = php_fpm; }
#     # { .backend = php_fpm2; }
# }

acl purge_allowed {
    "127.0.0.1";
    "192.168.1.0/24";  # 允許清理緩存的 IP (如管理後台、CI/CD)
}

sub vcl_recv {
    # 規範化 Host header
    set req.http.Host = regsub(req.http.Host, ":\d+$", "");

    # 正規化 Accept-Encoding (僅保留 gzip)
    if (req.http.Accept-Encoding) {
        if (req.http.Accept-Encoding ~ "gzip") { set req.http.Accept-Encoding = "gzip"; }
        else { unset req.http.Accept-Encoding; }
    }

    # 1. 清理請求 (PURGE 方法)
    if (req.method == "PURGE") {
        if (!client.ip ~ purge_allowed) { return (synth(405, "Not allowed.")); }
        return (purge);
    }

    # 2. 僅緩存 GET/HEAD
    if (req.method != "GET" && req.method != "HEAD") { return (pass); }

    # 3. 繞過緩存: 後台、登入、註冊、評論提交、POST、帶特定 Cookie
    if (req.url ~ "^/wp-(login|admin|cron|comments-post\.php|xmlrpc\.php)") { return (pass); }
    if (req.http.Cookie ~ "wordpress_logged_in_|wp-postpass_|comment_author_|woocommerce_items_in_cart|woocommerce_cart_hash") { return (pass); }
    if (req.http.Authorization || req.http.Cache-Control ~ "no-cache") { return (pass); }

    # 4. 靜態資源直接緩存 (移除 Cookie、Vary、Accept-Encoding)
    if (req.url ~ "\.(css|js|jpe?g|png|gif|ico|svg|woff2?|ttf|eot|pdf|zip|gz|rar|txt|xml|webp|avif)(\?v=\d+\.\d+\.\d+)?$") {
        unset req.http.Cookie;
        unset req.http.Vary;
        unset req.http.Accept-Encoding;
        return (hash);
    }

    # 5. HTML 頁面: 匿名用戶緩存,登入用戶繞過
    if (req.url ~ "^(/|/.*\.html?)$") {
        if (req.http.Cookie ~ "wordpress_logged_in_|wp-postpass_|comment_author_") { return (pass); }
        unset req.http.Cookie;  # 關鍵:移除 Cookie 才能緩存 HTML
        return (hash);
    }

    # 6. 其他動態請求預設繞過
    return (pass);
}

sub vcl_backend_response {
    # 1. 後端錯誤時服務過期內容 (優雅模式)
    if (beresp.status >= 500 && beresp.status < 600) {
        set beresp.grace = 1h;
        return (deliver);
    }

    # 2. 靜態資源: 長期緩存 (1年),移除 Set-Cookie
    if (bereq.url ~ "\.(css|js|jpe?g|png|gif|ico|svg|woff2?|ttf|eot|pdf|zip|gz|rar|txt|xml|webp|avif)(\?v=\d+\.\d+\.\d+)?$") {
        set beresp.ttl = 365d;
        set beresp.grace = 1h;
        unset beresp.http.Set-Cookie;
        return (deliver);
    }

    # 3. HTML 頁面: 短期緩存 (5-30分鐘視流量而定),移除 Set-Cookie,設優雅模式
    if (bereq.url ~ "^(/|/.*\.html?)$") {
        set beresp.ttl = 10m;      # 匿名頁面緩存 10 分鐘
        set beresp.grace = 1h;     # 後端掛掉繼續服務舊內容 1 小時
        unset beresp.http.Set-Cookie;
        # 可選: 依據 Vary 標籤區分緩存 (如移動端/桌面端)
        # if (beresp.http.Vary) { set beresp.http.Vary = regsub(beresp.http.Vary, "Cookie", ""); }
        return (deliver);
    }

    # 4. 其他 (如 JSON API、RSS) 短緩存或不緩存
    set beresp.ttl = 1m;
    set beresp.grace = 30s;
    return (deliver);
}

sub vcl_deliver {
    # 添加緩存狀態頭供調試/監控
    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT";
        set resp.http.X-Cache-Hits = obj.hits;
    } else {
        set resp.http.X-Cache = "MISS";
    }
    # 安全頭: 隱藏後端資訊
    unset resp.http.X-Powered-By;
    unset resp.http.Server;
    unset resp.http.Via;
    unset resp.http.X-Varnish;
    unset resp.http.Age;
    # 可選: 設定客戶端緩存策略
    # if (resp.http.Content-Type ~ "text/html") { set resp.http.Cache-Control = "public, max-age=300"; }
}

sub vcl_pipe {
    # 管道模式關閉連接,避免佔用後端連接
    set bereq.http.Connection = "close";
}

sub vcl_synth {
    # 自定義錯誤頁面 (可選)
    if (resp.status == 405) { set resp.http.Content-Type = "text/plain; charset=utf-8"; synthetic("PURGE not allowed"); }
    if (resp.status == 503) { set resp.http.Content-Type = "text/html; charset=utf-8"; synthetic({"

Service Unavailable

Backend maintenance.

"); } return (deliver); }

第四步:配置 Nginx 作為 SSL 終結與靜態文件服務 (/etc/nginx/conf.d/wordpress.conf)

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    return 301 https://$server_name$request_uri;  # 強制 HTTPS
}

server {
    listen 443 ssl http2;
    server_name yourdomain.com www.yourdomain.com;

    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    root /var/www/wordpress;
    index index.php;

    # 1. 靜態文件直接由 Nginx 高效服務 (關鍵優化)
    location ~* \.(css|js|jpe?g|png|gif|ico|svg|woff2?|ttf|eot|pdf|zip|gz|rar|txt|xml|webp|avif)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        access_log off;
        try_files $uri =404;
    }

    # 2. 動態請求代理給 Varnish (端口 8080)
    location / {
        proxy_pass https://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Port $server_port;
        proxy_cache_bypass $http_upgrade;  # WebSocket 支援
        proxy_http_version 1.1;
        proxy_read_timeout 90s;
        proxy_send_timeout 90s;
    }

    # 3. PHP 後端直連 (可選,繞過 Varnish 用於特定調試/管理)
    # location ~ \.php$ {
    #     fastcgi_pass unix:/run/php-fpm/www.sock;
    #     include fastcgi_params;
    #     fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    # }

    # 安全: 禁止訪問敏感文件
    location ~ /\. { deny all; }
    location ~* /(wp-config\.php|readme\.html|license\.txt) { deny all; }
}

第五步:WordPress 端配合優化

  1. 健康檢查端點:在 WordPress 根目錄建立 health_check.php:
    <?php echo "OK"; ?> (VCL probe 使用)。
  2. 緩存清理外掛:安裝 「Varnish HTTP Purge」 或 「WP Rocket」 (付費,含 Varnish 整合),發布/更新文章/頁面/評論時自動發送 PURGE 請求清理相關緩存。
  3. 設定 WP_HOME/WP_SITEURL 為 HTTPS:wp-config.php 添加:
    define('WP_HOME','https://yourdomain.com');
    define('WP_SITEURL','https://yourdomain.com');
  4. 反向代理頭修正:wp-config.php 添加 (獲取真實客戶端 IP):
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip_list = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $_SERVER['REMOTE_ADDR'] = trim($ip_list[0]); }

第六步:驗證與監控

  1. 測試緩存命中:
    curl -I -H "Host: yourdomain.com" https://127.0.0.1:8080/
    觀察 X-Cache: HIT (命中) 或 MISS (未命中)。首次訪問為 MISS,刷新應為 HIT。
  2. Varnish 統計:
    varnishstat (關鍵指標: MAIN.cache_hit, MAIN.cache_miss, MAIN.client_req, SMA.*.g_bytes 記憶體使用)。
    varnishtop -i ReqURL (熱門 URL)。
    varnishlog -g request -q 'ReqURL ~ "wp-admin"' (調試後台請求)。
  3. 日誌分析:
    varnishncsa -a -F '%h %l %u %t "%r" %s %b "%{Referer}i" "%{User-agent}i" %{X-Cache}o' (生成類 Apache 訪問日誌含緩存狀態)。

常見問題排查

現象可能原因排查方向
後台/登入頁面也被緩存VCL 未正確識別 Cookie 或 URL檢查 vcl_recv 中 Cookie 正則、URL 正則;確認瀏覽器開發者工具 Network 面板請求頭無 wordpress_logged_in_ Cookie 時才緩存。
緩存不生效 (全是 MISS)後端返回 Set-Cookie / Cache-Control: no-cache / Vary: Cookievarnishlog -g request -q 'RespHeader ~ "Set-Cookie"' 定位來源;VCL vcl_backend_response 中 unset beresp.http.Set-Cookie;檢查 PHP session.auto_start、外掛輸出 Cookie。
更新文章前台不顯示PURGE 請求未送達/失敗檢查外掛設定 Varnish IP:Port (通常 127.0.0.1:8080);VCL acl purge_allowed 包含 Web 伺服器 IP;Nginx proxy_pass 到 Varnish 正確;防火牆允許 8080 端口本地/內網訪問。
503 Backend fetch failed後端 (PHP-FPM) 掛掉、超時、連接數耗盡檢查 PHP-FPM 錯誤日誌、pm.max_children 設定、Varnish .first_byte_timeout、健康檢查端點可用性。
HTTPS 混合內容警告Nginx 未傳遞 X-Forwarded-Proto 或 WordPress 未識別確認 Nginx proxy_set_header X-Forwarded-Proto $scheme;;WP wp-config.php 處理該頭;強制 SSL 外掛 (Really Simple SSL)。

總結

在 CentOS/RHEL 系系統部署 **Varnish 7 LTS + Nginx (SSL/靜態) + PHP-FPM** 加速 WordPress,關鍵在於:

  1. **架構分層正確**:Nginx 終結 SSL/服務靜態 → Varnish 記憶體緩存動態 HTML → PHP-FPM 執行邏輯。
  2. **VCL 精準控制緩存邊界**:匿名 GET/HEAD 緩存,登入/後台/POST/動態 Cookie 繞過,靜態資源長緩存,HTML 短緩存+優雅模式。
  3. **緩存清理機制可靠**:WP 外掛發送 PURGE,VCL ACL 限制來源,確保內容更新即時可見。
  4. **監覺到位**:varnishstat、X-Cache 頭、日誌持續觀測命中率、後端健康、記憶體使用。

配置完成後,典型 WordPress 頁面響應時間可從 **500ms-2s 降至 20-80ms (HIT 時)**,伺服器負載大幅下降,輕鬆應對流量高峰。記得定期備份 /etc/varnish/ 配置,並隨 Varnish 小版本更新及時升級修補安全漏洞。

copyright © 萬盛學電腦網 all rights reserved