Configure Nginx FastCGI cache to serve WordPress pages without PHP

Configure the Nginx FastCGI cache for WordPress

The Nginx FastCGI cache is one of the biggest performance wins on a self-hosted WordPress server. Nginx saves the first HTML response for a URL to disk and serves the next requests for it straight from the file, without PHP and MySQL. On a cache hit the response time drops from hundreds of milliseconds to a few, and the CPU load falls because no PHP workers are used.

Problem: Every page view of an anonymous visitor runs PHP-FPM and MySQL again, even for identical pages, so the CPU load is high and responses are slow under traffic.

Solution: Define a cache zone in the http block, enable the cache in the PHP location of the site, and skip it for everything personal: logged-in users, commenters, POST requests, the cart and checkout.

The cache zone

In /etc/nginx/nginx.conf, inside http { }:

fastcgi_cache_path /var/cache/nginx/wordpress
    levels=1:2
    keys_zone=WORDPRESS:100m
    inactive=60m
    max_size=1g;

fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

keys_zone is the memory for the keys (1 MB holds about 8,000), max_size the disk limit, inactive how long an entry that nobody requests is kept. Nginx creates the folder itself.

The site configuration

In the server { } block of the site:

set $skip_cache 0;

# POST requests and URLs with a query string
if ($request_method = POST) { set $skip_cache 1; }
if ($query_string != "") { set $skip_cache 1; }

# Admin, login, feeds, sitemaps, REST
if ($request_uri ~* "/wp-admin/|/wp-login.php|/xmlrpc.php|/wp-json/|/feed/|sitemap") { set $skip_cache 1; }

# Logged-in users, commenters, password-protected posts, WooCommerce sessions
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in|woocommerce_items_in_cart|wp_woocommerce_session") {
    set $skip_cache 1;
}

# WooCommerce pages
if ($request_uri ~* "/cart/|/checkout/|/my-account/") { set $skip_cache 1; }

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

    fastcgi_cache WORDPRESS;
    fastcgi_cache_valid 200 301 60m;
    fastcgi_cache_bypass $skip_cache;
    fastcgi_no_cache $skip_cache;
    fastcgi_cache_use_stale error timeout updating http_500;

    add_header X-FastCGI-Cache $upstream_cache_status;
}

fastcgi_ignore_headers Set-Cookie from the zone settings means that responses with cookies are cached too, so the cookie conditions above are what keeps personal pages out of the cache. If a plugin of yours uses its own cookie for personalized content, add it to the list. fastcgi_cache_use_stale serves the old copy while PHP is failing or the entry is being refreshed.

Check the configuration and reload: sudo nginx -t && sudo systemctl reload nginx.

Check

curl -sI https://example.com/ | grep -i x-fastcgi-cache
curl -sI https://example.com/ | grep -i x-fastcgi-cache

The first request shows MISS, the second HIT. For a logged-in user (or with ?nocache=1) it must be BYPASS.

Purging

Without purging, visitors see an updated post only after fastcgi_cache_valid expires. The Nginx Helper plugin (rtCamp) purges the affected pages when a post is published, updated or commented. It can delete the cache files directly (set its cache path to the one above) or send purge requests, which needs the third-party ngx_cache_purge module (included in some builds, like nginx-extras on Debian/Ubuntu). With the module, the purge location must be closed to the outside:

location ~ /purge(/.*) {
    allow 127.0.0.1;
    deny all;
    fastcgi_cache_purge WORDPRESS "$scheme$request_method$host$1";
}

Without allow/deny anyone could empty your cache with a stream of requests.

NOTE: The cache is shared by all anonymous visitors, so anything personal on a cached page (a “Hello, John”, a mini cart, a nonce in a form) will be shown to everyone. Load such parts with JavaScript after the page, or exclude the pages from the cache.