2026年5月20日

2026年5月20日

WordPressのサーバーキャッシュを設定する方法(Nginx・Apache対応)

はじめに

サーバーキャッシュはWordPressのPHP実行とデータベースクエリをスキップし、HTMLを直接配信する最も効果的な高速化手法です。Nginxの fastcgi_cache やApacheの mod_cache を設定することで、ページ表示速度を劇的に改善できます。

症状・原因

  • ページの表示が遅く、TTFBが高い
  • アクセス集中時にサーバー負荷が高くなる
  • プラグインキャッシュだけでは不十分
  • コアウェブバイタル(LCP)のスコアが低い

解決手順

ステップ1:Nginx FastCGI Cacheを設定する

# /etc/nginx/nginx.conf または /etc/nginx/conf.d/cache.conf

# キャッシュゾーンの定義(httpブロック内)
fastcgi_cache_path /var/cache/nginx/wordpress
    levels=1:2
    keys_zone=wordpress_cache:100m
    inactive=60m
    max_size=1g;

fastcgi_cache_key "$scheme$request_method$host$request_uri";
# /etc/nginx/sites-available/your-site.conf(serverブロック内)

set $skip_cache 0;

# ログイン中・コメント投稿者はキャッシュをスキップ
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|logged_in") {
    set $skip_cache 1;
}

# POSTリクエスト・クエリ文字列付きURLはスキップ
if ($request_method = POST) { set $skip_cache 1; }
if ($query_string != "") { set $skip_cache 1; }

location ~ \.php$ {
    fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

    fastcgi_cache wordpress_cache;
    fastcgi_cache_valid 200 60m;       # 200レスポンスを60分キャッシュ
    fastcgi_cache_bypass $skip_cache;  # キャッシュをスキップする条件
    fastcgi_no_cache $skip_cache;      # キャッシュに保存しない条件
    add_header X-Cache-Status $upstream_cache_status; # HIT/MISS確認用
}

ステップ2:WordPress側でキャッシュパージを設定する

// functions.php

// 投稿更新時にNginxキャッシュをパージ
function mytheme_purge_nginx_cache(int $post_id): void {
    if (wp_is_post_revision($post_id) || wp_is_post_autosave($post_id)) {
        return;
    }

    $url = get_permalink($post_id);
    if (!$url) {
        return;
    }

    // Nginx Cache Purgeモジュールが有効な場合
    $purge_url = str_replace('https://', 'http://', $url);
    wp_remote_request($purge_url, ['method' => 'PURGE', 'timeout' => 5]);

    // トップページもパージ
    wp_remote_request(home_url('/'), ['method' => 'PURGE', 'timeout' => 5]);
}
add_action('save_post', 'mytheme_purge_nginx_cache');
add_action('comment_post', function(int $comment_id): void {
    $comment = get_comment($comment_id);
    if ($comment) {
        mytheme_purge_nginx_cache((int) $comment->comment_post_ID);
    }
});

ステップ3:Apacheの mod_cache を設定する

# /etc/apache2/sites-available/your-site.conf

# mod_cache / mod_cache_disk が必要
# a2enmod cache cache_disk headers

<IfModule mod_cache.c>
    CacheEnable disk /
    CacheRoot /var/cache/apache2/mod_cache_disk
    CacheDefaultExpire 3600
    CacheMaxExpire 86400
    CacheIgnoreNoLastMod On

    # ログインユーザー・POSTはキャッシュしない
    <IfModule mod_headers.c>
        Header always set Cache-Control "no-cache, no-store" env=nocache
    </IfModule>
</IfModule>
// functions.php: Apacheキャッシュヘッダー制御
function mytheme_set_cache_headers(): void {
    if (is_user_logged_in() || is_admin()) {
        header('Cache-Control: no-cache, no-store, must-revalidate');
        header('Pragma: no-cache');
        return;
    }

    if (is_singular() || is_front_page()) {
        // 公開ページは1時間キャッシュ
        header('Cache-Control: public, max-age=3600, s-maxage=3600');
        header('Vary: Accept-Encoding, Cookie');
    }
}
add_action('send_headers', 'mytheme_set_cache_headers');

ステップ4:wp-config.php でWordPressキャッシュを有効化

// wp-config.php

// オブジェクトキャッシュを有効化
define('WP_CACHE', true);

// キャッシュのデバッグ(本番では false)
define('WP_CACHE_DEBUG', false);

// Transient APIのキャッシュ有効期限を短縮
// (Redisなどオブジェクトキャッシュ未使用の場合)
define('WP_TRANSIENT_CLEANUP_INTERVAL', 3600);

ステップ5:キャッシュの動作確認

# curlでキャッシュHIT/MISSを確認
curl -I https://example.com/ | grep -i x-cache

# 1回目(MISS)→ 2回目(HIT)になればキャッシュが機能している
curl -I https://example.com/ 2>/dev/null | grep "X-Cache-Status"
# X-Cache-Status: MISS

curl -I https://example.com/ 2>/dev/null | grep "X-Cache-Status"
# X-Cache-Status: HIT

# キャッシュディレクトリの確認
ls -lh /var/cache/nginx/wordpress/

注意事項

  • ログイン中ユーザーには絶対にキャッシュを返してはいけません。$http_cookie の確認は必須です
  • WooCommerceやカート機能があるページ(/cart/, /checkout/, /my-account/)は必ずキャッシュから除外してください
  • キャッシュパージの仕組みがないと、記事更新後も古い内容が表示され続けます

まとめ

NginxはFastCGI Cacheで高速なページキャッシュを実現します。$skip_cache 変数でログインユーザーやPOSTリクエストを除外し、X-Cache-Status ヘッダーでHIT/MISSを確認します。投稿更新時には save_post フックからPURGEリクエストを送ってキャッシュを無効化します。

お気軽にご相談ください

お見積りへ お問い合わせへ