Redis 对象缓存是加快 WordPress 网站速度的最有效技术之一,特别是对于进行频繁 MySQL 数据库调用的网站——例如电子商务商店、会员网站或许多类别和小部件的内容繁重出版物。Redis 通过在 RAM 中存储数据库查询结果和 PHP 对象来工作,因此 WordPress 不必在每个页面请求上重复相同的查询。本指南将逐步指导你从头开始安装和配置 Redis 对象缓存,一直到验证它能正确工作并调整它以获得最大性能。

Redis 对象缓存如何与 WordPress 配合使用

WordPress 附带了内置的对象缓存 API,但默认情况下它只为单个 PHP 请求的生命周期存储数据。这意味着当请求结束时缓存被丢弃,下一个访问者完全相同的数据库查询再次触发。在具有繁重插件的网站上——页面生成器、WooCommerce、SEO 插件和自定义小部件——单个页面加载可以触发超过 100 个 MySQL 查询。

Redis 充当持久外部对象存储。因为它作为单独的进程运行并在 RAM 中存储数据,缓存在 PHP 请求间保存下来。当 WordPress 需要以前获取的数据时,它在微秒内从 Redis 检索它,而不是等待 MySQL 执行查询、从磁盘读取和返回结果。

开始前的系统要求

在 WordPress 可以使用 Redis 作为其对象缓存后端之前,你需要三个组件:

Component Minimum Version Notes
Redis Server Redis 4.0+ (6.x recommended) Requires VPS or dedicated server with root access
PHP Extension phpredis or predis phpredis (C extension) is faster; predis is a pure-PHP fallback
WordPress Plugin Redis Object Cache plugin Available free on WordPress.org (by Till Krüss)
Server RAM 1 GB total minimum Allocate 64–256 MB to Redis depending on traffic

If you are on shared hosting, check with your provider first — some managed hosting platforms expose a Redis endpoint without requiring server-level configuration. On a VPS, you have full root access and can install Redis exactly as described in this guide.

Step 1 — Install Redis Server on Ubuntu/Debian

Connect to your server via SSH and run the following commands:

sudo apt update
sudo apt install redis-server -y

After installation, open the main configuration file and make several important changes:

sudo nano /etc/redis/redis.conf

Find and update the following settings:

# Bind only to localhost for security
bind 127.0.0.1 ::1

# Tell Redis it is managed by systemd
supervised systemd

# Set a memory cap (adjust based on your available RAM)
maxmemory 128mb

# Eviction policy when the cache is full
maxmemory-policy allkeys-lru

# Optional but recommended: use a Unix socket for lower latency
unixsocket /var/run/redis/redis-server.sock
unixsocketperm 770

Save the file, then restart and enable Redis so it starts on boot:

sudo systemctl restart redis-server
sudo systemctl enable redis-server

# Verify Redis is running
sudo systemctl status redis-server

# Quick connectivity test
redis-cli ping
# Expected output: PONG

Step 2 — Install the PHP Redis Extension

WordPress needs a PHP extension to communicate with the Redis server. Check whether phpredis is already loaded:

php -m | grep redis

If nothing is returned, install the extension for your PHP version:

# For PHP 8.3 (change the version number to match your setup)
sudo apt install php8.3-redis -y

# Restart PHP-FPM to load the extension
sudo systemctl restart php8.3-fpm

# Confirm the extension is now loaded
php -m | grep redis
# Should output: redis

专业提示:如果你的服务器使用 cPanel 或 DirectAdmin,可能会有一个点击界面来启用 Redis PHP 扩展,位于"软件">"PHP 扩展"或"MultiPHP INI 编辑器"下。先检查控制面板——这可能会为你节省多个命令行步骤。

步骤 3 — 安装和配置 WordPress 插件

在 WordPress 管理员中,转到"插件">"添加新的"并搜索由 Till Krüss 提供的"Redis 对象缓存"。安装并激活它。

Next, open your site's wp-config.php file and add the following constants before the line that reads /* That's all, stop editing! */:

// Redis Object Cache configuration
define( 'WP_REDIS_HOST', '127.0.0.1' );
define( 'WP_REDIS_PORT', 6379 );

// If you enabled the Unix socket above, use this instead of HOST/PORT
// define( 'WP_REDIS_PATH', '/var/run/redis/redis-server.sock' );

// Redis database index (0–15). Use different indexes if multiple WordPress
// sites share the same Redis instance
define( 'WP_REDIS_DATABASE', 0 );

// Connection timeouts in seconds
define( 'WP_REDIS_TIMEOUT', 1 );
define( 'WP_REDIS_READ_TIMEOUT', 1 );

// Prefix to namespace cache keys — prevents collisions with other apps
define( 'WP_REDIS_PREFIX', 'mywp_' );

// Maximum cache TTL in seconds (0 = no expiry, relies on LRU eviction)
define( 'WP_REDIS_MAXTTL', 86400 );  // 24 hours

Save the file, then go to Settings > Redis in the WordPress admin and click Enable Object Cache. The plugin copies a drop-in file to wp-content/object-cache.php, which WordPress automatically uses as the persistent cache backend from this point on.

Step 4 — Verify the Cache Is Working

After enabling, the Settings > Redis screen should show:

You can also verify directly from the command line:

# View overall Redis statistics
redis-cli info stats

# Check memory usage
redis-cli info memory

# Count cached keys for your WordPress database
redis-cli -n 0 dbsize

# Watch live commands in real time (press Ctrl+C to stop)
redis-cli monitor

For deeper per-request analysis, install the Query Monitor plugin. It shows each Object Cache hit and miss and identifies which plugins are making the most database calls.

Advanced Tuning for Maximum Performance

Once basic caching is running, these additional configuration changes push performance even further:

Switch from TCP to Unix Socket

A Unix socket bypasses the TCP/IP stack entirely and communicates directly via the file system, reducing connection latency for local processes. First, add the web server user to the redis group:

sudo usermod -aG redis www-data

# Confirm the socket file exists
ls -la /var/run/redis/redis-server.sock

Then update wp-config.php to use the socket path instead of host and port:

// Comment out the TCP settings
// define( 'WP_REDIS_HOST', '127.0.0.1' );
// define( 'WP_REDIS_PORT', 6379 );

// Use the Unix socket
define( 'WP_REDIS_PATH', '/var/run/redis/redis-server.sock' );

Set a Redis Password

Even though Redis is bound to localhost, adding a password provides defence-in-depth against privilege escalation attacks:

# In /etc/redis/redis.conf
requirepass your-strong-password-here
# In wp-config.php
define( 'WP_REDIS_PASSWORD', 'your-strong-password-here' );

Choose the Right Eviction Policy

The allkeys-lru policy is the best choice for WordPress object caching. When Redis reaches its memory limit, it silently removes the least-recently-used keys instead of returning errors. This means WordPress continues to work normally even when the cache is full — it just re-fetches uncached data from the database and re-populates the cache naturally.

# Apply in real time without a restart
redis-cli config set maxmemory-policy allkeys-lru

# Check the current setting
redis-cli config get maxmemory-policy

Monitoring Redis Health Over Time

Ongoing monitoring helps you confirm that Redis is delivering value and catch problems early. The most important metric is the cache hit rate:

# Hit rate = hits / (hits + misses) × 100
redis-cli info stats | grep -E "keyspace_hits|keyspace_misses"

# Sample healthy output:
# keyspace_hits:185200
# keyspace_misses:9100
# Hit Rate: 185200 / (185200 + 9100) = 95.3%

A hit rate below 50% typically means maxmemory is too low, causing excessive eviction. Doubling the memory allocation usually resolves this. Also watch for a rising mem_fragmentation_ratio — if it exceeds 2.0, a Redis restart compacts memory and recovers performance:

redis-cli info memory | grep -E "used_memory_human|maxmemory_human|mem_fragmentation_ratio"

Common Problems and How to Fix Them

The following issues appear most often during setup and production use:

Frequently Asked Questions (FAQ)

What is the difference between Redis Object Cache and Page Cache?

Page Cache (such as WP Super Cache or LiteSpeed Cache) stores fully-rendered HTML pages on disk so they can be served without running PHP at all. Redis Object Cache operates at the PHP/MySQL layer, storing the results of database queries and PHP objects in RAM so PHP does not have to repeat the same DB queries on every request. Both can be used together and complement each other — Page Cache reduces PHP overhead while Object Cache reduces database overhead.

Can Redis be used on shared hosting?

It depends on the hosting provider. Some managed hosting platforms offer Redis as a configurable option, but most shared hosting plans do not provide a dedicated Redis server. If Redis is unavailable, Memcached can serve as a partial alternative. The most reliable solution is a VPS where you have root access to install and configure Redis yourself.

Do I need to flush the cache every time I update content in WordPress?

The Redis Object Cache plugin automatically invalidates the relevant cache keys when you save a post, page, or update any WordPress option. You do not normally need to flush the cache manually. However, if you notice stale data being displayed, you can flush the cache from Settings > Redis in the WordPress admin, or run wp cache flush via WP-CLI.

How much RAM does Redis use and can it slow down my server?

Redis uses RAM up to the maxmemory value set in redis.conf. For a typical WordPress site, 64MB to 256MB is usually sufficient. Because Redis operates entirely in memory with no disk I/O, it adds very little CPU overhead and will speed up your server rather than slow it down. The only scenario where performance degrades is when maxmemory is set too low, causing frequent key eviction that reduces cache effectiveness.

WordPress 优化托管

AsiaGB 托管支持 PHP 8.3、MySQL、LiteSpeed 缓存和 WordPress 工具包——起价仅 500 泰铢/年。

查看托管计划