WordPress 网站速度优化完整指南
网站速度直接影响用户体验和搜索引擎排名。Google 的核心 Web 指标(Core Web Vitals)已成为排名因素之一。本文将从服务器底层到前端展示,全面介绍在搬瓦工 VPS 上优化 WordPress 速度的方法。如果你还没有安装 WordPress,请先参考 WordPress 安装教程。
一、服务器层面优化
1.1 选择合适的 PHP 版本
PHP 8.x 相比 7.x 有显著的性能提升。查看并切换 PHP 版本:
# 查看当前 PHP 版本
php -v
# 安装 PHP 8.3
apt update
apt install php8.3-fpm php8.3-mysql php8.3-xml php8.3-curl php8.3-gd php8.3-mbstring php8.3-zip php8.3-intl php8.3-redis -y
# 切换 Nginx 使用新版 PHP
# 在 Nginx 站点配置中修改
# fastcgi_pass unix:/run/php/php8.3-fpm.sock;
1.2 优化 PHP-FPM 配置
根据搬瓦工 VPS 的内存调整 PHP-FPM 的进程池参数:
# 编辑 /etc/php/8.3/fpm/pool.d/www.conf
# 1GB 内存的推荐配置
pm = dynamic
pm.max_children = 10
pm.start_servers = 3
pm.min_spare_servers = 2
pm.max_spare_servers = 5
pm.max_requests = 500
# 2GB 内存的推荐配置
pm = dynamic
pm.max_children = 20
pm.start_servers = 5
pm.min_spare_servers = 3
pm.max_spare_servers = 10
pm.max_requests = 1000
重启 PHP-FPM 使配置生效:
systemctl restart php8.3-fpm
1.3 启用 OPcache
OPcache 将编译后的 PHP 代码缓存到内存中,避免重复编译:
# 编辑 /etc/php/8.3/fpm/conf.d/10-opcache.ini
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
opcache.enable_cli=0
opcache.jit_buffer_size=64M
opcache.jit=1255
PHP 8.x 的 JIT 编译器可以进一步提升性能。
1.4 优化 Nginx 配置
# 在 /etc/nginx/nginx.conf 中优化
worker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 4096;
multi_accept on;
use epoll;
}
http {
# 启用 Gzip 压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
gzip_min_length 1024;
# 启用 Brotli 压缩(如已安装模块)
# brotli on;
# brotli_comp_level 6;
# brotli_types text/plain text/css application/json application/javascript text/xml;
# 文件缓存
open_file_cache max=10000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
# 客户端缓存
client_max_body_size 64M;
client_body_buffer_size 128k;
}
1.5 配置 Nginx FastCGI 缓存
FastCGI 缓存是服务器级别的页面缓存,效率远高于插件缓存:
# 在 http 块中添加缓存区定义
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=WORDPRESS:100m inactive=60m max_size=1g;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
# 在 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/|/wp-login.php") { set $skip_cache 1; }
# 不缓存已登录用户
if ($http_cookie ~* "wordpress_logged_in") { set $skip_cache 1; }
location ~ \.php$ {
fastcgi_cache WORDPRESS;
fastcgi_cache_valid 200 60m;
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
add_header X-FastCGI-Cache $upstream_cache_status;
}
创建缓存目录并重载 Nginx:
mkdir -p /var/cache/nginx
nginx -t && systemctl reload nginx
二、数据库优化
2.1 优化 MySQL/MariaDB 配置
# 编辑 /etc/mysql/mysql.conf.d/mysqld.cnf
[mysqld]
# InnoDB 缓冲池大小(建议为可用内存的 50-70%)
innodb_buffer_pool_size = 512M
innodb_log_file_size = 128M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
# 查询缓存(MySQL 8.0 已移除,MariaDB 仍支持)
query_cache_type = 1
query_cache_size = 64M
query_cache_limit = 2M
# 临时表和排序缓冲
tmp_table_size = 64M
max_heap_table_size = 64M
sort_buffer_size = 4M
# 连接设置
max_connections = 100
wait_timeout = 300
systemctl restart mysql
2.2 定期清理数据库
使用 WP-CLI 清理冗余数据:
# 清理文章修订版本
wp post delete $(wp post list --post_type='revision' --format=ids --allow-root) --force --allow-root
# 清理垃圾评论
wp comment delete $(wp comment list --status=spam --format=ids --allow-root) --force --allow-root
# 清理过期 transients
wp transient delete --expired --allow-root
# 优化数据库表
wp db optimize --allow-root
设置 cron 任务自动清理(每周执行一次):
crontab -e
# 添加以下行
0 3 * * 0 cd /var/www/html && wp transient delete --expired --allow-root && wp db optimize --allow-root
2.3 使用 Redis 对象缓存
Redis 对象缓存可以减少 50% 以上的数据库查询。详细配置请参考 WordPress 插件配置指南 中 Redis 章节。
三、前端资源优化
3.1 静态资源长期缓存
在 Nginx 中为静态文件设置长期浏览器缓存:
location ~* \.(jpg|jpeg|png|gif|ico|svg|webp|avif)$ {
expires 365d;
add_header Cache-Control "public, immutable";
access_log off;
}
location ~* \.(css|js)$ {
expires 30d;
add_header Cache-Control "public";
access_log off;
}
location ~* \.(woff|woff2|ttf|eot)$ {
expires 365d;
add_header Cache-Control "public, immutable";
access_log off;
}
3.2 图片懒加载
WordPress 5.5 及以上版本已内置图片懒加载功能。确保在 functions.php 中没有禁用它:
// 确认懒加载已启用(默认启用,如果被禁用可以重新添加)
add_filter('wp_lazy_loading_enabled', '__return_true');
3.3 预加载关键资源
在 functions.php 中添加关键资源的预加载标签:
function mytheme_preload_resources() {
// 预加载关键字体
echo '<link rel="preload" href="' . get_stylesheet_directory_uri() . '/assets/fonts/main.woff2" as="font" type="font/woff2" crossorigin>' . "\n";
// 预连接 CDN 域名
echo '<link rel="preconnect" href="https://cdn.example.com">' . "\n";
echo '<link rel="dns-prefetch" href="https://cdn.example.com">' . "\n";
}
add_action('wp_head', 'mytheme_preload_resources', 1);
四、WordPress 内部优化
4.1 减少心跳 API 频率
// 在 functions.php 中添加
function mytheme_heartbeat_settings($settings) {
$settings['interval'] = 60; // 默认 15 秒改为 60 秒
return $settings;
}
add_filter('heartbeat_settings', 'mytheme_heartbeat_settings');
// 在非编辑页面禁用心跳
function mytheme_disable_heartbeat() {
global $pagenow;
if ($pagenow != 'post.php' && $pagenow != 'post-new.php') {
wp_deregister_script('heartbeat');
}
}
add_action('init', 'mytheme_disable_heartbeat', 1);
4.2 禁用不需要的功能
// 移除 emoji 支持
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
// 移除 XML-RPC(如果不需要远程发布)
add_filter('xmlrpc_enabled', '__return_false');
// 移除 REST API 链接
remove_action('wp_head', 'rest_output_link_wp_head');
// 限制文章修订版本数量
define('WP_POST_REVISIONS', 5); // 在 wp-config.php 中添加
五、性能测试与监控
优化完成后,使用以下工具测试效果:
- Google PageSpeed Insights:测试 Core Web Vitals 各项指标。
- GTmetrix:提供详细的加载瀑布图分析。
- WebPageTest:多地点、多浏览器的真实环境测试。
在命令行中快速测试响应时间:
# 测试首字节时间(TTFB)
curl -o /dev/null -s -w "TTFB: %{time_starttransfer}s\nTotal: %{time_total}s\n" https://your-domain.com
# 查看缓存是否生效
curl -I https://your-domain.com | grep -i "x-fastcgi-cache"
总结
WordPress 速度优化是一个系统工程,需要从服务器、数据库、PHP、前端等多个层面同步进行。在搬瓦工 VPS 上,你拥有完整的服务器控制权,可以实施本文介绍的所有优化措施。通过 PHP 8.3 + OPcache JIT、Nginx FastCGI 缓存、Redis 对象缓存的组合,可以让 WordPress 的 TTFB 降低到 100ms 以下。建议同时参考 WordPress 安全加固教程 和 插件配置指南,全面提升网站质量。选购搬瓦工 VPS 请查看 全部方案,购买时使用优惠码 NODESEEK2026 可享受 6.77% 的折扣,通过 bwh81.net 进入官网购买。