Skip to content

nginx FastCGI cache for WordPress at production scale

A correctly configured fastcgi_cache turns a 200ms TTFB into a 20ms TTFB without touching PHP. The wrong config caches admin pages, logged-in views, or whole sessions. Here is the config we ship.

The marketing team launches a campaign, traffic on the homepage jumps 8×, and PHP-FPM workers saturate inside three minutes. You scale up the application tier and it holds, but the cost line item now looks bad. The right answer is rarely “more PHP” — it’s “less PHP.” A well-tuned fastcgi_cache directive on the nginx tier turns 95% of the homepage requests into a sendfile from disk, with WordPress never invoked. The trap is that the wrong config will happily cache the admin dashboard, logged-in user views, or a checkout page mid-session.

What’s happening

fastcgi_cache is nginx’s built-in cache for upstream FastCGI responses. When a request matches a configured cacheable key and the cached entry is fresh, nginx serves the cached response directly without ever talking to PHP-FPM. The entry sits on local disk (or tmpfs), keyed by whatever you compose in fastcgi_cache_key.

The config has four moving parts:

1. The shared memory zone and disk path — declared once in the http {} block with fastcgi_cache_path. The shared memory holds the key index; the disk path holds the cached bodies. Size both based on traffic shape (a busy WP site might want 1-2 GB of cached body on tmpfs).

2. The cache key — fastcgi_cache_key composes the unique identifier. The default cookbook key is $scheme$request_method$host$request_uri. That’s enough for most sites; multisite networks need to include the $http_host carefully, and stores running A/B tests need to factor in the variant cookie.

3. The bypass conditions — fastcgi_cache_bypass and fastcgi_no_cache skip the cache for cases that must always hit PHP: logged-in users, admin pages, POST requests, WooCommerce cart/checkout, the WordPress preview parameter.

4. The purge mechanism — ngx_cache_purge (a separate nginx module) exposes a URI that, when hit with the right key, invalidates the corresponding cache entry. A WordPress plugin (Nginx Helper, fastcgi-cache-purge) hooks into save_post, publish_post, and comment_post to call the purge URI on content change.

The hardest mistake to spot is fastcgi_no_cache not matching when it should. If you write if ($http_cookie ~ "wordpress_logged_in") but the cookie name is actually wordpress_logged_in_HASH, the regex misses and nginx caches the logged-in homepage with a wp-admin bar visible. The first time anonymous traffic hits it, they see another user’s session. That’s a P0 incident discovered hours later when the support inbox lights up.

How to verify

Confirm the cache is actually in use:

# Look for the cache status in response headers
curl -I -H "Pragma: no-cache" https://www.example.com/
# Look for X-Cache-Status: HIT/MISS/BYPASS/EXPIRED/STALE

The first request should be MISS, the second HIT. If you only ever see BYPASS, your conditional is matching when it shouldn’t. If you see MISS repeatedly, the key is varying (probably a cookie or query string in the key).

Inspect the cache directory:

# Cache file count and total size
ls /var/cache/nginx/fastcgi/ | wc -l
du -sh /var/cache/nginx/fastcgi/

# Find a specific cached entry (md5 of the cache key)
echo -n "httpsGETwww.example.com/" | md5sum
# Result: f5e... — find the file in the subdirectory tree
find /var/cache/nginx/fastcgi/ -name "f5e*"

Check the cache loader and manager status in the error log:

grep -E "cache loader|cache manager" /var/log/nginx/error.log

For hit rate over time:

# Tail the access log filtered by X-Cache-Status
tail -f /var/log/nginx/access.log | awk '{print $NF}'

Verify the bypass conditions catch all logged-in patterns:

# As a logged-in user
curl -I -b "wordpress_logged_in_abc123=user|expires|hmac" \
  https://www.example.com/some-page/
# Should show X-Cache-Status: BYPASS

# WooCommerce cart
curl -I https://www.example.com/cart/
# Should show BYPASS, not HIT

The fix

The full nginx config we ship for WordPress sites with anonymous-dominant traffic (publishing, content marketing, brochure). For stores, the same config applies with additional bypass rules; see the WooCommerce notes below.

nginx.conf — top-level cache declaration

# /etc/nginx/nginx.conf — inside http {} block

# Cache path: 1 GB on disk, 512 MB key index in shared memory
fastcgi_cache_path /var/cache/nginx/fastcgi
                   levels=1:2
                   keys_zone=WORDPRESS:512m
                   inactive=60m
                   max_size=1g
                   use_temp_path=off;

fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_use_stale error timeout invalid_header updating http_500 http_503;
fastcgi_cache_background_update on;
fastcgi_cache_lock on;
fastcgi_cache_lock_timeout 5s;
fastcgi_cache_revalidate on;

# Expose cache status in response headers (remove in production if exposing
# this is a concern, or keep behind a debug header)
add_header X-Cache-Status $upstream_cache_status always;

The interesting flags:

  • levels=1:2 — two-level directory tree, keeps the inode count per directory sane.
  • inactive=60m — entries unused for 60 minutes are evicted regardless of TTL.
  • max_size=1g — when total cache exceeds this, the cache manager evicts least-recently-used.
  • use_temp_path=off — write directly into the cache dir, avoid a copy from /var/lib/nginx/tmp.
  • cache_use_stale — if upstream is down, serve stale. Critical for graceful degradation.
  • cache_background_update — serve stale while fetching fresh in the background.
  • cache_lock — only one worker fetches a cold entry; the rest wait. Prevents thundering herd.

Server block — full WordPress site

# /etc/nginx/conf.d/example.com.conf

server {
    listen 443 ssl http2;
    server_name www.example.com example.com;

    root /home/wpuser/public_html;
    index index.php index.html;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # Set the bypass flag based on request characteristics
    set $skip_cache 0;

    # POST requests, query strings (search, etc.), preview, admin, login
    if ($request_method = POST)              { set $skip_cache 1; }
    if ($query_string != "")                 { set $skip_cache 1; }
    if ($request_uri ~* "/wp-admin/|/wp-.*\.php|/feed/|sitemap(_index)?\.xml") {
        set $skip_cache 1;
    }
    if ($request_uri ~* "preview=true|woocommerce-cart|woocommerce-checkout|add-to-cart") {
        set $skip_cache 1;
    }

    # Logged-in cookies (this regex is the one that bites — match all variants)
    if ($http_cookie ~* "wordpress_logged_in_|wp-postpass_|comment_author_|woocommerce_items_in_cart|woocommerce_cart_hash") {
        set $skip_cache 1;
    }

    # WooCommerce / EDD: skip cache once a cart has items
    if ($cookie_woocommerce_items_in_cart = "1") { set $skip_cache 1; }

    # Static files
    location ~* \.(jpg|jpeg|png|webp|gif|ico|css|js|woff2|svg)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
        access_log off;
    }

    # WordPress permalinks
    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    # PHP processing with FastCGI cache
    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        fastcgi_cache_bypass $skip_cache;
        fastcgi_no_cache $skip_cache;

        fastcgi_cache WORDPRESS;
        fastcgi_cache_valid 200 301 302 60m;
        fastcgi_cache_valid 404 1m;
        fastcgi_cache_min_uses 1;

        # Long enough that purge-on-publish does the heavy lifting,
        # short enough that a missed purge is corrected within an hour
    }

    # Cache purge endpoint — only callable from localhost or the plugin
    location ~ /purge(/.*) {
        allow 127.0.0.1;
        deny all;
        fastcgi_cache_purge WORDPRESS "$scheme$request_method$host$1";
    }

    # Deny access to .ht* files
    location ~ /\.ht { deny all; }

    # Deny access to wp-config and xmlrpc
    location = /wp-config.php { deny all; }
    location = /xmlrpc.php { deny all; }
}

ngx_cache_purge module

The standard nginx package on most distros doesn’t include the purge module. You need either:

  • Build nginx from source with --add-module=/path/to/ngx_cache_purge
  • Use a package like nginx-extras (Debian/Ubuntu) that bundles it
  • Run nginx-plus (commercial), which includes a paid alternative

For AlmaLinux:

# Add the nginx mainline repo, install nginx-mod-cache-purge if available
# Otherwise, build from source — runbook is one-time
dnf install -y gcc make pcre-devel zlib-devel openssl-devel
NGINX_VERSION=1.24.0
curl -O https://nginx.org/download/nginx-$NGINX_VERSION.tar.gz
git clone https://github.com/FRiCKLE/ngx_cache_purge.git
tar xzf nginx-$NGINX_VERSION.tar.gz
cd nginx-$NGINX_VERSION
./configure --with-compat --add-dynamic-module=../ngx_cache_purge \
            --with-http_ssl_module --with-http_v2_module
make modules
cp objs/ngx_http_cache_purge_module.so /etc/nginx/modules/

Then in nginx.conf:

load_module modules/ngx_http_cache_purge_module.so;

WordPress side — Nginx Helper

Install the Nginx Helper plugin (rtCamp). In Settings → Nginx Helper:

  • Enable purge: Yes
  • Caching method used: nginx Fastcgi cache
  • Purge method: Using a GET request to PURGE/url
  • Purge cache settings:
    • Purge homepage on new post and comment — yes
    • Purge post on edit and comment — yes
    • Purge archives, taxonomies, author — yes for content-driven sites

The plugin will hit https://www.example.com/purge/<path> on every save_post, which the location ~ /purge(/.*) block converts into a fastcgi_cache_purge.

Test the purge:

# As localhost on the host
curl -X GET http://127.0.0.1/purge/some-post-slug/
# Should return 200 with HTML "Successful purge" or empty body

WooCommerce considerations

For stores, the bypass list grows:

# Add to the $skip_cache section
if ($request_uri ~* "/cart/|/checkout/|/my-account/|/wc-api/") {
    set $skip_cache 1;
}
if ($http_cookie ~* "woocommerce_cart_hash|wp_woocommerce_session_") {
    set $skip_cache 1;
}

Crucially, WooCommerce product pages can still be cached for anonymous visitors. The “Add to cart” AJAX endpoint at /?wc-ajax=add_to_cart is a POST and bypasses automatically. Once the session cookie is set, all subsequent pages bypass.

Cache warming

After deploys or major content changes, prime the cache:

# Walk the sitemap and request each URL
curl -s https://www.example.com/wp-sitemap.xml \
  | grep -oP '<loc>\K[^<]+' \
  | xargs -P 8 -I {} curl -sI {} -o /dev/null

When to use this vs. Varnish or Cloudflare APO

fastcgi_cache is the cheapest and most controllable layer because it lives on the same box as nginx. It pre-empts the entire PHP stack but only on the server doing the work. For multi-origin setups behind a load balancer, the cache is per-origin — request distribution determines hit rate. Above that scale, add an edge cache (Cloudflare, Fastly, Varnish) on top; fastcgi_cache stays as the origin shield.


Stack Harbor configures fastcgi_cache with proper purge wiring as part of Enterprise WordPress onboarding, alongside the monitoring and on-call coverage that catches a stuck cache before it serves stale checkout pages. If your origin is taking too much PHP load and you’d like a second pair of eyes on the config, we can review it.