Skip to content

FastCGI caching in Nginx — when to cache PHP responses and when not to

How to use fastcgi_cache to serve PHP-FPM responses from disk, the cache keys that matter, and the bypass rules that prevent caching authenticated traffic.

FastCGI caching is Nginx’s way of remembering a PHP-FPM response and serving the next identical request from disk without touching PHP. For a WordPress or other CMS site that does heavy work to render each request, it is the single biggest win available — Nginx can serve thousands of requests per second from cache where PHP-FPM would manage tens. The trick is that the bypass rules are unforgiving: get them wrong and you serve a logged-in user’s dashboard to anonymous visitors.

How to verify

See whether anything is being cached today:

sudo nginx -T | grep -E 'fastcgi_cache|fastcgi_cache_path'
ls -la /var/cache/nginx/ 2>/dev/null
curl -sI https://example.com/ | grep -i x-cache-status
sudo grep -E 'X-FastCGI-Cache' /var/log/nginx/access.log | tail

If you have set up an add_header X-Cache-Status $upstream_cache_status always; (recommended), the first curl shows HIT, MISS, BYPASS, EXPIRED, or STALE. Without that header you are flying blind.

What’s happening

fastcgi_cache_path declares an on-disk cache (or tmpfs) with a key namespace, max size, and inactivity timeout. Each cached response is a file whose name is a hash of fastcgi_cache_key. Nginx hits the cache before forwarding to PHP-FPM; on a HIT, PHP is not invoked at all. On MISS, Nginx forwards, stores the response, and serves it.

The bypass logic is the contract between cache and PHP. Anything that should not be cached — authenticated requests, POSTs, requests with no-cache cookies — must be matched by fastcgi_cache_bypass and ideally also fastcgi_no_cache. The bypass causes Nginx to skip the cache for this request; no_cache prevents the response from being stored.

The procedure

  1. Declare the cache zone in nginx.conf under http {}:
    fastcgi_cache_path /var/cache/nginx/fastcgi
        levels=1:2
        keys_zone=PHPCACHE:64m
        inactive=60m
        max_size=2g
        use_temp_path=off;
    
    fastcgi_cache_key "$scheme$request_method$host$request_uri";
    64m of keys zone holds ~500 000 entries. max_size=2g is the disk cap; eviction is LRU. use_temp_path=off avoids a cross-filesystem move on cache writes.
  2. Wire it into the PHP location:
    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
        include fastcgi_params;
    
        fastcgi_cache         PHPCACHE;
        fastcgi_cache_valid   200 301 302 60m;
        fastcgi_cache_valid   404 1m;
        fastcgi_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
        fastcgi_cache_lock    on;
    
        fastcgi_cache_bypass  $no_cache_bypass;
        fastcgi_no_cache      $no_cache_bypass;
    
        add_header X-Cache-Status $upstream_cache_status always;
    }
  3. Define $no_cache_bypass in the server block — this is where you encode “do not cache logged-in users”:
    set $no_cache_bypass 0;
    if ($request_method = POST)           { set $no_cache_bypass 1; }
    if ($query_string ~* "nocache")        { set $no_cache_bypass 1; }
    if ($http_cookie ~* "wordpress_logged_in_|wp-postpass_|comment_author_") { set $no_cache_bypass 1; }
    if ($request_uri ~* "/wp-admin/|/wp-login.php|sitemap.*\.xml") { set $no_cache_bypass 1; }
    WordPress is the most common case — the cookie patterns above are what every “Nginx + WP cache” example uses.
  4. Test the bypass rules. Log in, hit the homepage, check X-Cache-Status — it should be BYPASS. Log out (clear cookies), hit again — it should be MISS (first time) then HIT.
  5. Purging. Open-source Nginx does not ship explicit purge — you either let entries expire on inactive, delete the cache files (find /var/cache/nginx/fastcgi -type f -delete), or compile in the third-party ngx_cache_purge module. We deliberately do not auto-purge on every content edit; we accept a 60-minute staleness window in exchange for predictable cache behaviour.
  6. Monitor hit ratio. awk '$status==200 {print}' /var/log/nginx/access.log | grep -oE 'X-Cache: [A-Z]+' | sort | uniq -c or a Prometheus exporter that watches $upstream_cache_status. A healthy WP cache hits >85% during peak.
  7. Resize the cache. If max_size fills, evictions accelerate and HIT-rate drops. Watch df on the cache filesystem and tune up.

Common pitfalls

  • Caching /wp-admin/ because the bypass regex is wrong. The first logged-in user serves their nonce to everyone. Verify with curl -sb 'wordpress_logged_in_xyz=1' ….
  • fastcgi_cache_key that omits $host on a multi-tenant box. Tenant A and tenant B share a single cached homepage.
  • fastcgi_cache_use_stale not set — when PHP-FPM goes down, Nginx returns 502 instead of serving slightly stale content.
  • Cache directory on the same disk as the database, both contending under load. Move the cache to tmpfs (small) or a separate disk.
  • Forgetting fastcgi_cache_lock on; on a high-traffic page. A cold cache + 1000 concurrent first hits = 1000 simultaneous PHP requests for the same response. Lock forces only one to fill the cache.

In the engagements we run, FastCGI cache is the highest-impact change we make on a slow PHP host — typically dropping PHP-FPM CPU by 70–90%. We template the bypass rules per stack (WordPress vs. custom) and monitor hit-rate as a first-class signal in managed operations.