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
- Create a cache directory – Run
sudo mkdir -p /var/run/nginx-cacheand thensudo chown www-data:www-data /var/run/nginx-cache(replacewww-datawith your PHP-FPM user if different). This directory will hold the cached pages. - Edit your Nginx site configuration – Open the file, typically
/etc/nginx/sites-available/your-site, withsudo nano /etc/nginx/sites-available/your-site. - Add cache settings in the
httpblock – If you have multiple sites, add these to/etc/nginx/nginx.confinside thehttp { }block. If it’s a single site, you can place them in theserver { }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.
- Configure the cache in the
location ~ \.php$block – Find the block that handles PHP requests (usuallylocation ~ \.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_validsets how long to cache responses with status codes 200, 301, and 302 (60 minutes here). Thefastcgi_cache_use_staleserves stale copies if the backend fails. Thefastcgi_cache_lockprevents multiple requests from hitting PHP simultaneously for the same page. - Define the
$skip_cachevariable – Add thismapblock in yourhttpblock (or in thenginx.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
nocacheparameter. Adjust the patterns to match your site. - Set cache headers for logged-in users – Add this inside the
server { }block, before thelocationblocks: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.
- 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.
- Reload Nginx – Test the configuration with
sudo nginx -t, then reload withsudo systemctl reload nginx(orsudo service nginx reload). - 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 withcurl -I http://your-site.com– look forX-FastCGI-Cache: HITorMISS(you may need to add the header manually in thelocation ~ \.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
ifinsidelocationblocks – Nginx’sifis tricky; always placeset $skip_cachein 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 like1hor even24hif 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 -tto ensure your config is valid. Verify that thefastcgi_cache_pathandfastcgi_cachedirectives 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
ifstatement. The cookie name might be different (e.g.,wordpress_logged_in_followed by a hash). Usegrepin 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_lockcausing timeouts. Try increasingfastcgi_cache_lock_timeout(default 5s) or disabling the lock. - Cache is too large – If the cache directory fills up, reduce the
inactivetime or thefastcgi_cache_validduration. You can also set amax_sizein thefastcgi_cache_pathdirective.
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
- Microsoft Surface Duo: The Foldable Phone Story
- Samsung SM-T813 Hard Reset: Step-by-Step Guide
- Mafia Clash Codes: Real Meanings & Usage
- Remove Programs from Mac: Full Uninstall Guide
- Project Sentinel Morning Digest: Data Stack Failure Alerts
- Best KVM VPS Hosting: Top Picks & Guide