User Agents

Web browsers and everyday web tech, explained

Nginx FastCGI Cache Setup: Step-by-Step Guide

· 5 min read · Cookies and Cache

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. Define a cache zone – Open your main Nginx config (usually /etc/nginx/nginx.conf) and add a fastcgi_cache_path directive inside the http block. 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;
    Replace MYCACHE with a name you'll reference later. levels=1:2 creates a two-level directory structure for performance. inactive=60m means files not accessed for 60 minutes are removed. max_size=500m caps total cache size.
  2. Create the cache directory – Ensure the path exists and is writable by Nginx. Run:
    sudo mkdir -p /var/cache/nginx
    sudo chown -R www-data:www-data /var/cache/nginx (adjust user to match your Nginx user, often nginx or www-data).
  3. Add cache directives to your site's server block – Edit your site config (e.g., /etc/nginx/sites-available/mysite). Inside the server block, 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).
  4. 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.
  5. Bypass caching for logged-in users or admin pages – Use fastcgi_cache_bypass and fastcgi_no_cache to skip the cache for cookies or specific URIs. For example, for WordPress:
    fastcgi_cache_bypass $skip_cache;
    fastcgi_no_cache $skip_cache;
    Define $skip_cache in the server block using a map or an if condition. A common approach: set it to 1 if the request has a cookie like wordpress_logged_in or the URI contains /wp-admin.
  6. Add cache headers for debugging – Append headers to see if the cache is working:
    add_header X-FastCGI-Cache $upstream_cache_status;
    This will show HIT, MISS, or BYPASS in the response headers.
  7. Reload Nginx – Test your config and reload:
    sudo nginx -t
    sudo systemctl reload nginx (or sudo service nginx reload).
  8. Test the cache – Visit your site twice with curl -I or browser dev tools. The first request should show MISS, the second HIT in the X-FastCGI-Cache header.

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=2 or tracking parameters, the cache key must include $request_uri to 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_valid to a few seconds (e.g., 5s) to absorb traffic spikes while keeping content fresh.
  • Monitor cache hit ratio – Use the X-FastCGI-Cache header or Nginx's stub_status to 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_zone to isolate cache and prevent one site from evicting another's entries.

Troubleshooting

  • Cache not working (always MISS) – Check if fastcgi_cache_bypass is accidentally set to 1 for all requests. Also ensure the fastcgi_cache_key matches the actual request. Test with a simple static page first.
  • Nginx fails to start – Run sudo nginx -t to see syntax errors. Common issues: missing fastcgi_cache_path in http block, or invalid path permissions.
  • Cache serves stale content – Increase inactive time? No, that's for eviction. For freshness, lower fastcgi_cache_valid or implement purging. Also check if your app sends Cache-Control: no-cache headers – Nginx respects those by default unless you override with fastcgi_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 the if or map is correctly set. Use curl -H "Cookie: wordpress_logged_in=test" -I to test.
  • Cache files not being created – Check permissions on the cache directory. Also verify that the FastCGI response doesn't have Set-Cookie headers – by default, Nginx won't cache responses with Set-Cookie unless you add fastcgi_ignore_headers Set-Cookie; (use with caution).
  • HTTPS pages not caching – Ensure your cache key includes $scheme to differentiate HTTP and HTTPS. Also check that your SSL termination is before Nginx (e.g., using a proxy) or that Nginx sees the https scheme 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.