Sunday, March 9, 2025

Cấu Hình Redis Cache và Proxy Cache cho WordPress với Nginx

-

1. Giới Thiệu

Caching là một trong những giải pháp tối ưu hiệu suất quan trọng nhất cho WordPress. Việc sử dụng Redis Cache giúp lưu trữ dữ liệu truy vấn từ database vào bộ nhớ RAM, trong khi Proxy Cache giúp giảm tải server bằng cách lưu trữ các phản hồi HTTP từ WordPress.

Bài viết này sẽ hướng dẫn bạn từng bước cấu hình Redis Cache và Proxy Cache cho WordPress trên Nginx.

2. Cài Đặt Redis Cache

Redis Cache giúp WordPress giảm tải truy vấn vào MySQL bằng cách lưu trữ dữ liệu truy vấn vào bộ nhớ RAM, giúp cải thiện tốc độ tải trang.

Bước 1: Cài đặt Redis và PHP Redis Extension

apt update && apt install redis-server php-redis -y

Bước 2: Kích hoạt Redis và thiết lập chế độ giám sát bởi systemd

systemctl enable redis --now
sed -i 's/supervised no/supervised systemd/' /etc/redis/redis.conf
systemctl restart redis

Bước 3: Cấu hình Redis trong WordPress

Mở file wp-config.php và thêm các dòng sau:

define( 'WP_CACHE', true ); // Kích hoạt cache cho WordPress
define( 'WP_MEMORY_LIMIT', '4096M' );
define( 'ALTERNATE_WP_CRON', true );
define( 'WP_AUTO_UPDATE_CORE', false );
define( 'WP_REDIS_HOST', '10.10.99.251' );
define( 'WP_REDIS_PORT', 6379 );
define( 'WP_REDIS_DATABASE', 0 );
define( 'WP_REDIS_TIMEOUT', 1 );
define( 'WP_REDIS_READ_TIMEOUT', 1 );
define( 'WP_REDIS_SCHEME', 'tcp' );
define( 'WP_REDIS_GLOBAL_GROUPS', ['users', 'userlogins'] );
define( 'WP_REDIS_NON_PERSISTENT', true );

Bước 4: Kích hoạt Redis Cache trong WordPress

Sau khi chỉnh sửa wp-config.php, bạn cần cài đặt plugin Redis Object Cache từ kho plugin của WordPress. Sau đó, truy cập vào phần Cài đặt > Redis, nhấn node “Enable Object Cache” để kích hoạt.

3. Cấu Hình Proxy Cache với Nginx

Ngoài Redis Cache, bạn có thể sử dụng Proxy Cache để lưu trữ phản hồi HTTP từ WordPress, giúp giảm tải server và cải thiện tốc độ tải trang.

Bước 1: Tạo thư mục lưu trữ cache

mkdir -p /etc/nginx/cache_fastcgi
mkdir -p /etc/nginx/cache_proxy
mkdir -p /var/cache/nginx/client_temp
mkdir -p /var/cache/nginx/static_cache
mkdir -p /var/cache/nginx/proxy_cache

Bước 2: Cấp quyền cho Nginx

chown -R www-data:www-data /var/cache/nginx
chmod -R 755 /var/cache/nginx

Bước 3: Chỉnh sửa cấu hình Nginx

Mở file /etc/nginx/nginx.conf và thêm:

fastcgi_cache_path /etc/nginx/cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m use_temp_path=off;
fastcgi_cache_path /etc/nginx/cache_fastcgi levels=1:2 keys_zone=FCGI_CACHE:100m inactive=60m use_temp_path=off;
proxy_cache_path /var/cache/nginx/static_cache levels=1:2 keys_zone=STATIC_CACHE:10m inactive=7d max_size=1g;
proxy_cache_path /var/cache/nginx/proxy_cache levels=1:2 keys_zone=PROXY_CACHE:100m inactive=30m max_size=5g;

Ví dụ.

cat > /etc/nginx/nginx.conf << 'OEF'
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 10240;
    multi_accept on;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 4096;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    gzip on;
    gzip_disable "msie6";
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    fastcgi_cache_path /etc/nginx/cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m use_temp_path=off;
    fastcgi_cache_path /etc/nginx/cache_fastcgi levels=1:2 keys_zone=FCGI_CACHE:100m inactive=60m use_temp_path=off;
    proxy_cache_path /var/cache/nginx/static_cache levels=1:2 keys_zone=STATIC_CACHE:10m inactive=7d max_size=1g;
    proxy_cache_path /var/cache/nginx/proxy_cache levels=1:2 keys_zone=PROXY_CACHE:100m inactive=30m max_size=5g;


    include /etc/nginx/conf.d/*.conf;
}
OEF

Bước 4: Cấu hình Virtual Host cho WordPress

Mở file config cho domain WordPress của bạn (/etc/nginx/conf.d/yourdomain.conf) và thêm:

server {
    listen 443 ssl;
    server_name wiki.hoanghd.com;

    ssl_certificate /etc/nginx/letsencrypt/wiki.hoanghd.com.pem;
    ssl_certificate_key /etc/nginx/letsencrypt/wiki.hoanghd.com.pem;
    ssl_trusted_certificate /etc/nginx/letsencrypt/wiki.hoanghd.com.pem;

    location / {
        proxy_pass http://wiki-wordpress;
        proxy_http_version 1.1;
        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_cache PROXY_CACHE;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        proxy_cache_valid 200 60m;
        proxy_cache_use_stale error timeout updating invalid_header http_500;
        proxy_cache_lock on;
        add_header X-Proxy-Cache $upstream_cache_status;
    }

    location ~* \.(css|js|gif|jpe?g|png|ico|woff2?|ttf|svg|eot|mp4|webm|ogg|ogv|zip|pdf)$ {
        proxy_pass http://wiki-wordpress;
        proxy_cache STATIC_CACHE;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        proxy_cache_valid 200 365d;
        proxy_cache_use_stale error timeout updating;
        proxy_cache_lock on;
        add_header Cache-Control "public, max-age=31536000, immutable";
        add_header X-Static-Proxy-Cache $upstream_cache_status;
    }
}

Ví dụ.

cat > /etc/nginx/conf.d/wiki.hoanghd.com.conf << 'OEF'
server {
    listen 443 ssl;
    http2 on;
    server_name wiki.hoanghd.com;

    ssl_certificate /etc/nginx/letsencrypt/wiki.hoanghd.com.pem;
    ssl_certificate_key /etc/nginx/letsencrypt/wiki.hoanghd.com.pem;
    ssl_trusted_certificate /etc/nginx/letsencrypt/wiki.hoanghd.com.pem;

    # Redirect HTTP → HTTPS
    if ($scheme = http) {
        return 301 https://$host$request_uri;
    }

    # Logs
    access_log /var/log/nginx/wiki_access.log combined;
    error_log /var/log/nginx/wiki_error.log warn;

    # Proxy all request to backend (no use root)
    location / {
        proxy_pass http://wiki-wordpress;
        proxy_http_version 1.1;
        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 Cache
        proxy_cache PROXY_CACHE;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        proxy_cache_valid 200 60m;
        proxy_cache_use_stale error timeout updating invalid_header http_500;
        proxy_cache_lock on;
        add_header X-Proxy-Cache $upstream_cache_status;
    }

    # Caching file static qua Proxy (CSS, JS, IMAGE, fonts)
    location ~* \.(?:css|js|gif|jpe?g|png|ico|woff2?|ttf|svg|eot|mp4|webm|ogg|ogv|zip|pdf)$ {
        proxy_pass http://wiki-wordpress;
        proxy_http_version 1.1;
        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;

        # Cache riêng cho file tĩnh
        proxy_cache STATIC_CACHE;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        proxy_cache_valid 200 365d;
        proxy_cache_use_stale error timeout updating;
        proxy_cache_lock on;

        add_header Cache-Control "public, max-age=31536000, immutable";
        add_header X-Static-Proxy-Cache $upstream_cache_status;
    }

    # Proxy Cache for REST API
    location /wp-json/ {
        proxy_pass http://wiki-wordpress;
        proxy_cache PROXY_CACHE;
        proxy_cache_valid 200 10m;
        proxy_cache_use_stale error timeout updating;
        proxy_cache_lock on;
        add_header X-Proxy-Cache $upstream_cache_status;
    }

    # Block access to hidden files
    location ~ /\. {
        deny all;
    }

    error_page 403 /error403.html;
    location = /error403.html {
        internal;
        proxy_pass http://wiki-wordpress/error403.html;
    }
}
OEF

Bước 5: Kiểm tra và khởi động lại Nginx

nginx -t && systemctl restart nginx

4. Kiểm Tra Hoạt Động Của Cache

Sau khi hoàn thành cài đặt, bạn có thể kiểm tra cache hoạt động như sau:

Kiểm tra Redis Cache

redis-cli -h 10.10.99.251 -p 6379

Sau đó, chạy lệnh:

keys *

Nếu bạn thấy danh sách các khóa, điều đó có nghĩa là Redis Cache đang hoạt động.

Kiểm tra Proxy Cache

Dùng curl để kiểm tra:

curl -I https://wiki.hoanghd.com/

Nếu thấy dòng X-Proxy-Cache: HIT, nghĩa là Proxy Cache đã hoạt động.

5. Kết Luận

Bằng cách kết hợp Redis Cache và Proxy Cache, bạn có thể tối ưu hóa tốc độ tải trang WordPress một cách đáng kể. Redis giúp giảm tải truy vấn vào MySQL, trong khi Proxy Cache giúp lưu trữ các phản hồi HTTP, giảm số lượng request đến server. Điều này đặc biệt quan trọng đối với các website có lượng truy cập lớn.

Chúc bạn thành công! 🚀

LEAVE A REPLY

Please enter your comment!
Please enter your name here

4,956FansLike
256FollowersFollow
223SubscribersSubscribe
spot_img

Related Stories