perkun.eu Services Portfolio Blog About Contact PL
← Blog

2/14/2022

nginx FastCGI cache for WordPress — a practical guide

TL;DR: FastCGI cache serves cached pages directly from nginx — PHP and MySQL are never invoked. WordPress loads in < 200ms. Configuration takes 30 minutes.

WordPress with PHP and MySQL can generate a page in 100–300ms. At 1,000 visits per day that’s unnoticeable. At 10,000 — the server starts to struggle. FastCGI cache solves the problem radically: instead of generating the page on every request, nginx serves a previously generated version from disk.

nginx configuration

In the main nginx configuration file (before the server block):

fastcgi_cache_path /tmp/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";

In the server block:

set $skip_cache 0;

# Don't cache POST requests, logged-in users, WooCommerce cart
if ($request_method = POST) { set $skip_cache 1; }
if ($query_string != "") { set $skip_cache 1; }
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|woocommerce_items_in_cart|woocommerce_cart_hash") {
    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;
    # ... rest of fastcgi_pass configuration
}

Cache invalidation

The cache must be cleared after publishing a new post. The Nginx Cache plugin integrates with WordPress and clears the appropriate cache key on every publish and update.

Alternatively: call nginx -s reload or delete the /tmp/nginx-cache directory via cron after midnight if the content doesn’t change too often.

Verification

The X-FastCGI-Cache: HIT header means nginx served from cache. MISS — PHP was involved. BYPASS — cache was skipped (e.g. logged-in user).

curl -I https://yourshop.com/ | grep X-FastCGI-Cache
# X-FastCGI-Cache: HIT

Results

Typical improvement: from 300ms to < 50ms for cached pages. PageSpeed Insights — an increase of 20–40 points. For WooCommerce, remember that the cart, checkout, and account pages should not be cached — hence the cookie-based exclusions.