keepcalculator

06 Numbers and Powers

Nginx FastCGI Cache for WordPress: Setup Guide

Card No. 06·70619 · Updated · Standard formula, shown below

This guide walks you through setting up FastCGI caching in Nginx for WordPress, which stores fully rendered pages as static files and serves them to visitors without re-executing PHP. The result is dramatically faster page loads and lower server load, especially under traffic spikes. You’ll need root or sudo access to your server, an Nginx configuration file for your site, and a WordPress installation already running.

What You’ll Need

  • A server running Nginx (any modern version, 1.7+ recommended)
  • WordPress installed and configured with PHP-FPM
  • SSH access with sudo privileges
  • A text editor (nano, vim, or similar)

Step-by-Step

  1. Create a cache directory – Run sudo mkdir -p /var/run/nginx-cache and then sudo chown www-data:www-data /var/run/nginx-cache (replace www-data with your PHP-FPM user if different). This directory will hold the cached pages.
  2. Edit your Nginx site configuration – Open the file, typically /etc/nginx/sites-available/your-site, with sudo nano /etc/nginx/sites-available/your-site.
  3. Add cache settings in the http block – If you have multiple sites, add these to /etc/nginx/nginx.conf inside the http { } block. If it’s a single site, you can place them in the server { } block. The directives are:
    fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m;
    fastcgi_cache_key "$scheme$request_method$host$request_uri";

    This defines the cache path, the shared memory zone (100MB), and the cache key based on the URL.

  4. Configure the cache in the location ~ \.php$ block – Find the block that handles PHP requests (usually location ~ \.php$ { ... }). Add these lines inside it:
    fastcgi_cache WORDPRESS;
    fastcgi_cache_valid 200 301 302 60m;
    fastcgi_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
    fastcgi_cache_lock on;
    fastcgi_cache_bypass $skip_cache;
    fastcgi_no_cache $skip_cache;

    The fastcgi_cache_valid sets how long to cache responses with status codes 200, 301, and 302 (60 minutes here). The fastcgi_cache_use_stale serves stale copies if the backend fails. The fastcgi_cache_lock prevents multiple requests from hitting PHP simultaneously for the same page.

  5. Define the $skip_cache variable – Add this map block in your http block (or in the nginx.conf):
    map $request_uri $skip_cache {
        default 0;
        ~*/wp-admin/ 1;
        ~*/wp-json/ 1;
        ~*/cart/ 1;
        ~*/checkout/ 1;
        ~*/my-account/ 1;
        ~*/wc-api/ 1;
        ~*\?add-to-cart= 1;
        ~*\?nocache= 1;
    }

    This tells Nginx not to cache admin pages, REST API, WooCommerce cart/checkout, and any URL with nocache parameter. Adjust the patterns to match your site.

  6. Set cache headers for logged-in users – Add this inside the server { } block, before the location blocks:
    set $skip_cache 0;
    if ($http_cookie ~* "wordpress_logged_in|wp-postpass|comment_author") {
        set $skip_cache 1;
    }

    This ensures logged-in users and commenters never get a cached page, preventing stale content.

  7. Add cache-bypass for POST requests – Add this in the server { } block:
    if ($request_method = POST) {
        set $skip_cache 1;
    }

    This prevents caching form submissions.

  8. Reload Nginx – Test the configuration with sudo nginx -t, then reload with sudo systemctl reload nginx (or sudo service nginx reload).
  9. Verify caching works – Visit your site’s homepage, then check if a cache file was created: sudo find /var/run/nginx-cache -type f. You should see files appear. You can also check response headers with curl -I http://your-site.com – look for X-FastCGI-Cache: HIT or MISS (you may need to add the header manually in the location ~ \.php$ block: add_header X-FastCGI-Cache $upstream_cache_status;).

Common Mistakes

  • Not excluding logged-in users – Without the cookie check, logged-in users will see cached pages, causing confusing behavior (e.g., admin bar not showing, comments not appearing).
  • Cache key too broad – If you don’t include the method or scheme in the cache key, HTTPS and HTTP pages might mix, or POST requests could be served from cache.
  • Forgetting to purge cache – When you update a post or change a theme, the old cache remains. You need a purge mechanism (see Tips).
  • Using if inside location blocks – Nginx’s if is tricky; always place set $skip_cache in the server block, not inside location blocks, to avoid unexpected behavior.
  • Not testing with a staging site – Always test on a staging site first to avoid breaking production.

Tips

  • Purge cache on WordPress updates – Install a plugin like “Nginx Helper” or “WP Fastest Cache” that can automatically purge the cache when you update posts, pages, or settings.
  • Use a longer cache time for static content – You can set fastcgi_cache_valid 200 301 302 60m; to something like 1h or even 24h if your content doesn’t change often.
  • Monitor cache hit rate – Add add_header X-FastCGI-Cache $upstream_cache_status; to see if requests are hitting (HIT) or missing (MISS). Use this to fine-tune.
  • Use a separate cache path per site – If you host multiple WordPress sites, create separate directories (e.g., /var/run/nginx-cache/site1) to avoid conflicts.
  • Consider using a CDN – FastCGI caching is great, but a CDN can offload even more traffic and improve global latency.

Troubleshooting

  • Cache not working – Check that the cache directory exists and is writable. Run sudo nginx -t to ensure your config is valid. Verify that the fastcgi_cache_path and fastcgi_cache directives are in the correct blocks.
  • Pages not updating – This is likely because you’re not purging the cache. Manually delete the cache files with sudo rm -rf /var/run/nginx-cache/* and reload Nginx. Then set up automatic purging.
  • Logged-in users see cached pages – Double-check the cookie pattern in the if statement. The cookie name might be different (e.g., wordpress_logged_in_ followed by a hash). Use grep in your browser’s developer tools to see the exact cookie name.
  • Cache file permissions – If Nginx can’t write to the cache directory, you’ll see errors in the Nginx error log. Ensure the directory is owned by the Nginx user (usually www-data).
  • Getting 502 or 504 errors – This might be due to fastcgi_cache_lock causing timeouts. Try increasing fastcgi_cache_lock_timeout (default 5s) or disabling the lock.
  • Cache is too large – If the cache directory fills up, reduce the inactive time or the fastcgi_cache_valid duration. You can also set a max_size in the fastcgi_cache_path directive.

Frequently Asked Questions

How do I purge the cache manually?

Delete all files in the cache directory: sudo rm -rf /var/run/nginx-cache/*, then reload Nginx. For automatic purging, use a plugin like Nginx Helper.

Can I use this with WooCommerce?

Yes, but you must exclude cart, checkout, and my-account pages (as shown in the $skip_cache map). Also, ensure that dynamic content like product stock levels is not cached incorrectly.

Will this work with SSL/HTTPS?

Yes, as long as the cache key includes $scheme (which it does in our example). This ensures separate cache entries for HTTP and HTTPS.

Does this cache work for mobile vs desktop?

By default, no. If your site serves different content based on user agent, you need to include a mobile detection in the cache key, e.g., $http_user_agent – but this reduces cache efficiency.

What happens when a page is being updated?

With fastcgi_cache_use_stale, Nginx will serve the stale cached version while the backend updates. This prevents users from seeing errors during updates.

Is FastCGI caching better than a plugin like WP Super Cache?

FastCGI caching is more efficient because it works at the Nginx level, not in PHP. It can handle higher traffic with less overhead. However, plugins offer more features like mobile detection and easy purging.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →