Nginx FastCGI Cache Setup: Step-by-Step Guide
In this article
Configuring Nginx with FastCGI cache dramatically speeds up dynamic sites (like WordPress, PHP, or Python apps) by storing rendered pages as static files and serving them directly, bypassing the backend. This reduces server load and improves response times, often by 10-100x. You'll need a working Nginx server with a FastCGI backend (like PHP-FPM) already configured. This guide walks through enabling, tuning, and troubleshooting the cache.
What You'll Need
- A server with Nginx installed (version 1.7.3+ recommended for full cache control).
- A working FastCGI backend (e.g., PHP-FPM) configured with Nginx for your site.
- Root or sudo access to edit Nginx configuration files.
- Basic familiarity with Nginx config syntax.
Step-by-Step
- Define a cache zone – Open your main Nginx config (usually
/etc/nginx/nginx.conf) and add afastcgi_cache_pathdirective inside thehttpblock. This sets the cache directory and its size limits.fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=MYCACHE:100m inactive=60m max_size=500m;
ReplaceMYCACHEwith a name you'll reference later.levels=1:2creates a two-level directory structure for performance.inactive=60mmeans files not accessed for 60 minutes are removed.max_size=500mcaps total cache size. - Create the cache directory – Ensure the path exists and is writable by Nginx. Run:
sudo mkdir -p /var/cache/nginxsudo chown -R www-data:www-data /var/cache/nginx(adjust user to match your Nginx user, oftennginxorwww-data). - Add cache directives to your site's server block – Edit your site config (e.g.,
/etc/nginx/sites-available/mysite). Inside theserverblock, add:fastcgi_cache MYCACHE;fastcgi_cache_key "$scheme$request_method$host$request_uri";
This key uniquely identifies each cached page. Include the request method to avoid caching POST requests (which are usually dynamic). - Set cache validity – Define how long to keep cached responses. Add:
fastcgi_cache_valid 200 301 302 60m;fastcgi_cache_valid 404 5m;
This caches successful responses (200, 301, 302) for 60 minutes, and 404s for 5 minutes. Add more lines for other status codes as needed. - Bypass caching for logged-in users or admin pages – Use
fastcgi_cache_bypassandfastcgi_no_cacheto skip the cache for cookies or specific URIs. For example, for WordPress:fastcgi_cache_bypass $skip_cache;fastcgi_no_cache $skip_cache;
Define$skip_cachein theserverblock using a map or an if condition. A common approach: set it to 1 if the request has a cookie likewordpress_logged_inor the URI contains/wp-admin. - Add cache headers for debugging – Append headers to see if the cache is working:
add_header X-FastCGI-Cache $upstream_cache_status;
This will showHIT,MISS, orBYPASSin the response headers. - Reload Nginx – Test your config and reload:
sudo nginx -tsudo systemctl reload nginx(orsudo service nginx reload). - Test the cache – Visit your site twice with
curl -Ior browser dev tools. The first request should showMISS, the secondHITin theX-FastCGI-Cacheheader.
Common Mistakes
- Forgetting to create the cache directory – Nginx will fail to start or throw a permission error if the path doesn't exist or isn't writable.
- Using a generic cache key – If you omit the request method or host, you might serve wrong cached content for HTTPS vs HTTP or for different domains.
- Caching admin or user-specific pages – Without bypass rules, logged-in users see other users' data, or admin changes don't appear. Always exclude cookies and admin URIs.
- Setting too long a validity – A 24h cache might be fine for static content, but for dynamic sites it can cause stale content. Use moderate times (5-60 minutes) unless you have a purge mechanism.
- Ignoring query strings – If your site uses
?page=2or tracking parameters, the cache key must include$request_urito avoid serving the same page for different queries.
Tips
- Use a purge tool – Install a cache purge module (like
ngx_cache_purge) or create a script that deletes cache files when content changes. This avoids waiting for expiration. - Enable microcaching – For high-traffic sites, set
fastcgi_cache_validto a few seconds (e.g., 5s) to absorb traffic spikes while keeping content fresh. - Monitor cache hit ratio – Use the
X-FastCGI-Cacheheader or Nginx'sstub_statusto check how often you're hitting the cache. Aim for >90% for static-heavy sites. - Combine with gzip – Enable gzip compression for cached responses to reduce bandwidth. Nginx can compress cached content on the fly.
- Use separate cache zones for different sites – If you host multiple apps, give each its own
keys_zoneto isolate cache and prevent one site from evicting another's entries.
Troubleshooting
- Cache not working (always MISS) – Check if
fastcgi_cache_bypassis accidentally set to 1 for all requests. Also ensure thefastcgi_cache_keymatches the actual request. Test with a simple static page first. - Nginx fails to start – Run
sudo nginx -tto see syntax errors. Common issues: missingfastcgi_cache_pathinhttpblock, or invalid path permissions. - Cache serves stale content – Increase
inactivetime? No, that's for eviction. For freshness, lowerfastcgi_cache_validor implement purging. Also check if your app sendsCache-Control: no-cacheheaders – Nginx respects those by default unless you override withfastcgi_ignore_headers. - Logged-in users see cached pages – Your bypass condition isn't working. Inspect the cookie name (e.g.,
wordpress_logged_in) and ensure theiformapis correctly set. Usecurl -H "Cookie: wordpress_logged_in=test" -Ito test. - Cache files not being created – Check permissions on the cache directory. Also verify that the FastCGI response doesn't have
Set-Cookieheaders – by default, Nginx won't cache responses withSet-Cookieunless you addfastcgi_ignore_headers Set-Cookie;(use with caution). - HTTPS pages not caching – Ensure your cache key includes
$schemeto differentiate HTTP and HTTPS. Also check that your SSL termination is before Nginx (e.g., using a proxy) or that Nginx sees thehttpsscheme correctly.
Frequently Asked Questions
Does FastCGI cache work with PHP-FPM?
Yes, it's the most common use case. The cache stores the output of PHP scripts after they're executed, so subsequent requests skip PHP entirely.
How do I clear the cache?
Delete the files in the cache directory: sudo rm -rf /var/cache/nginx/*. For selective purging, install the ngx_cache_purge module and use a special URL like /purge/your-page.
Can I cache POST requests?
Technically yes, but it's almost never a good idea because POST requests usually change data. The default cache key includes $request_method, so POSTs are cached separately, but you should bypass them entirely.
What's the difference between FastCGI cache and proxy_cache?
FastCGI cache is for FastCGI backends (like PHP-FPM). Proxy_cache is for HTTP proxies (like Node.js or Apache). The directives are similar but apply to different upstream connections.
Will caching break my site's dynamic features?
If you cache everything, yes. That's why you need bypass rules for logged-in users, admin panels, and any page that shows user-specific data (cart, profile, etc.).
How do I know if a page is served from cache?
Add add_header X-FastCGI-Cache $upstream_cache_status; and check the response headers. It will show HIT, MISS, EXPIRED, or BYPASS.