WordPress 每次请求都要执行 PHP 解释器 + MySQL 查询,高并发时服务器 CPU 会被压垮。Varnish Cache 是专为 Web 加速设计的反向代理缓存服务器,将第一次请求的 HTML 响应缓存在内存中,后续相同请求直接从内存返回——响应时间从 300ms 降至 3ms,性能提升百倍,且完全绕过 PHP 和 MySQL。
一、Varnish 工作位置
<code">
外部请求
│ :80/:443
▼
Nginx(处理 SSL 终结,将 HTTP 转给 Varnish)
│ :6081(HTTP)
▼
Varnish Cache(内存缓存层)
│ 缓存未命中时,回源
▼
Nginx/Apache + PHP-FPM(实际执行 PHP 的后端)
│ :8080
▼
MySQL / Redis
二、安装 Varnish
<code"># 添加 Varnish 官方仓库(Ubuntu 22.04) curl -s https://packagecloud.io/varnishcache/varnish75/gpgkey \ | gpg --dearmor > /usr/share/keyrings/varnish.gpg echo "deb [signed-by=/usr/share/keyrings/varnish.gpg] \ https://packagecloud.io/varnishcache/varnish75/ubuntu jammy main" \ > /etc/apt/sources.list.d/varnish.list apt update && apt install -y varnish varnishd -V
<code"># /etc/varnish/varnish.params(Varnish 启动参数) VARNISH_VCL_CONF=/etc/varnish/default.vcl VARNISH_LISTEN_PORT=6081 # Varnish 监听端口 VARNISH_ADMIN_LISTEN_ADDRESS=127.0.0.1 VARNISH_ADMIN_LISTEN_PORT=6082 VARNISH_SECRET_FILE=/etc/varnish/secret VARNISH_STORAGE="malloc,512m" # 内存缓存大小(根据服务器内存调整) VARNISH_USER=varnish VARNISH_GROUP=varnish
三、VCL 配置文件(WordPress 智能缓存策略)
<code"># /etc/varnish/default.vcl
vcl 4.1;
import std;
import directors;
# 后端:PHP 应用服务器
backend default {
.host = "127.0.0.1";
.port = "8080";
.connect_timeout = 5s;
.first_byte_timeout = 90s;
.between_bytes_timeout = 60s;
# 后端健康检查
.probe = {
.url = "/health";
.timeout = 5s;
.interval = 10s;
.window = 5;
.threshold = 3;
}
}
# ── 接收请求(决定是否缓存)──
sub vcl_recv {
# 处理 X-Forwarded-For
if (req.restarts == 0) {
if (req.http.X-Forwarded-For) {
set req.http.X-Forwarded-For = req.http.X-Forwarded-For + ", " + client.ip;
} else {
set req.http.X-Forwarded-For = client.ip;
}
}
# 非 GET/HEAD 请求不缓存(POST 总是透传到后端)
if (req.method != "GET" && req.method != "HEAD") {
return(pass);
}
# WordPress 管理后台不缓存
if (req.url ~ "^/wp-(admin|cron|login)") {
return(pass);
}
# WordPress 登录用户不缓存(Cookie 中包含 wordpress_logged_in)
if (req.http.Cookie ~ "wordpress_logged_in") {
return(pass);
}
# WooCommerce:购物车非空时不缓存(woocommerce_items_in_cart)
if (req.http.Cookie ~ "woocommerce_items_in_cart") {
return(pass);
}
# WooCommerce 特定路径不缓存
if (req.url ~ "^/(cart|checkout|my-account|wc-api)") {
return(pass);
}
# AJAX 请求透传
if (req.url ~ "\?.*action=") {
return(pass);
}
# 清除不必要的 Cookie(减少缓存碎片化)
# 只保留 WordPress 相关 Cookie
if (req.http.Cookie) {
set req.http.Cookie = ";" + req.http.Cookie;
set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";");
set req.http.Cookie = regsuball(req.http.Cookie,
";(comment_author|wordpress_[^;]+|PHPSESSID)=", "; \1=");
set req.http.Cookie = regsuball(req.http.Cookie, ";[^ ][^;]*", "");
set req.http.Cookie = regsuball(req.http.Cookie, "^[; ]+|[; ]+$", "");
if (req.http.Cookie == "") {
unset req.http.Cookie;
}
}
# 静态资源可以缓存(忽略 Cookie)
if (req.url ~ "\.(css|js|png|jpg|jpeg|webp|gif|ico|woff2|woff|svg|mp4)(\?.*)?$") {
unset req.http.Cookie;
return(hash);
}
return(hash);
}
# ── 处理后端响应(决定缓存时长)──
sub vcl_backend_response {
# 静态资源缓存 1 天
if (bereq.url ~ "\.(css|js|png|jpg|jpeg|webp|gif|ico|woff2)(\?.*)?$") {
set beresp.ttl = 1d;
set beresp.grace = 6h;
unset beresp.http.Set-Cookie;
}
# HTML 页面缓存 4 小时
if (beresp.http.Content-Type ~ "text/html") {
if (beresp.status == 200) {
set beresp.ttl = 4h;
set beresp.grace = 1h; # grace 期内即使 TTL 过期也先返回旧缓存,后台异步更新
}
}
# 不缓存含 Set-Cookie 的响应
if (beresp.http.Set-Cookie) {
set beresp.uncacheable = true;
set beresp.ttl = 120s;
return(deliver);
}
# 不缓存 4xx/5xx 错误
if (beresp.status >= 400) {
set beresp.uncacheable = true;
set beresp.ttl = 30s;
}
}
# ── 返回响应(添加调试头)──
sub vcl_deliver {
# 添加缓存命中状态头(X-Cache: HIT/MISS)
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";
}
# 生产环境移除 Via 头(隐藏 Varnish)
unset resp.http.Via;
unset resp.http.X-Varnish;
}
# ── 缓存清除接口(WordPress 插件发布时主动清除)──
sub vcl_purge {
return(synth(200, "Purged"));
}
sub vcl_recv {
# PURGE 请求(只允许本地发起)
if (req.method == "PURGE") {
if (client.ip != "127.0.0.1") {
return(synth(405, "Method Not Allowed"));
}
return(purge);
}
}
四、Nginx 前置 SSL 配置
<code"># /etc/nginx/sites-available/yourdomain.com
# Nginx 处理 SSL,转发给 Varnish(HTTP)
# 后端:PHP 应用(Varnish 回源用)
server {
listen 8080;
server_name yourdomain.com;
root /var/www/wordpress;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_param HTTPS on; # 告诉 WordPress 是 HTTPS
}
}
# 前端:HTTPS → Varnish
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;
location / {
proxy_pass http://127.0.0.1:6081;
proxy_set_header Host $http_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 https;
proxy_read_timeout 300s;
}
}
五、WordPress 配置 Varnish 清除缓存
<code"># 安装 Varnish HTTP Purge 插件(WordPress 插件库搜索)
# 插件在文章发布/更新时自动向 Varnish 发送 PURGE 请求
# wp-config.php 添加(告知 Varnish 监听端口)
define('VHP_VARNISH_IP', '127.0.0.1');
define('VHP_VARNISH_PORT', 6081);
# 手动清除单个 URL 的缓存
curl -X PURGE -H "Host: yourdomain.com" http://127.0.0.1:6081/
# 清除所有缓存(慎用)
varnishadm "ban req.url ~ ."
六、监控缓存命中率
<code"># 实时统计
watch -n 2 'varnishstat -1 -f MAIN.cache_hit -f MAIN.cache_miss -f MAIN.client_req'
# 计算命中率
varnishstat -1 | grep -E "cache_hit|cache_miss" | awk '
BEGIN{hit=0;miss=0}
/cache_hit/{hit=$1}
/cache_miss/{miss=$1}
END{printf "命中率: %.1f%% (hit=%d miss=%d)\n", hit/(hit+miss)*100, hit, miss}'
# 查看当前缓存的对象
varnishadm "ban.list"
七、实测效果
| 测试场景 | 无 Varnish | 有 Varnish(缓存命中) |
|---|---|---|
| WordPress 首页响应时间 | 280ms | 3ms |
| WooCommerce 商品页 | 350ms | 4ms |
| 100并发 RPS(首页) | 48 | 12,000+ |
| 服务器 CPU(100并发) | 85% | 8% |
八、总结
Varnish 是专为 HTTP 缓存设计的工具,在 WordPress/WooCommerce 场景下缓存命中率通常可以达到 90% 以上,绝大多数请求在内存中直接返回,服务器可以用同等硬件支撑 10 倍以上的并发流量。香港服务器上部署 Nginx(SSL)+ Varnish(缓存)+ PHP-FPM(后端)的三层架构,是高流量 WordPress 站点的经典生产配置。
