Nginx FastCGI Cache for Heavy PHP
Most PHP performance fires follow the exact same script. Traffic spikes, a handful of crawlers discover your faceted catalog, and suddenly an eight-core PHP-FPM box sits pinned at 85% CPU. Nothing in the slow log looks broken, yet PHP workers burn seven cores rebuilding identical HTML ninety times a second for anonymous visitors who aren't even signed in.
Teams routinely throw bigger instances at traffic that shouldn't reach PHP at all. If you already terminate TLS and route requests through Nginx, you already have a fast page cache built into your stack. Turning on FastCGI microcaching with fastcgi_cache_use_stale updating regularly cuts PHP-FPM CPU by 80% on read-heavy apps—no Varnish tier, no extra TCP hops, and no extra daemon to babysit at 3 a.m.
The catch is session safety. One careless fastcgi_ignore_headers line copied from an old forum thread can cache a logged-in response and serve Alice's account page to Bob. Here is the exact setup I run in production to cut PHP CPU by four-fifths while keeping authenticated sessions isolated.
Why Microcaching Beats Tuning PHP-FPM Alone
OPcache and an object cache are baseline hygiene, not shields against anonymous traffic spikes. Even with OPcache hot and Redis object cache memory eviction tuned cleanly, every uncached anonymous GET still forces PHP-FPM to boot the runtime, wire up the service container, evaluate middleware, hydrate models, and render templates. On a realistic WordPress, WooCommerce, or Symfony codebase, that baseline CPU tax runs 45ms to 160ms per request.
At 250 anonymous requests per second and 80ms of PHP CPU each, you need twenty full CPU cores just to stand still. Put a fifteen-second FastCGI microcache in front of the Unix socket and that math collapses. One PHP worker pays the 80ms render cost, Nginx stores the response, and the next 3,749 visitors in that window get served straight out of Linux page cache in under a millisecond.
Running Nginx directly as a caching reverse proxy over FastCGI also keeps your topology simple. You retain native HTTP/2 and HTTP/3 termination, skip localhost proxy loops, and preserve strict per-pool Unix socket boundaries—a trade-off worth weighing if you've compared multi-tenant stacks like OpenLiteSpeed versus Nginx PHP isolation.
Configuring the Cache Zone Without Starving Disk or RAM
Declare the cache zone in the http context inside /etc/nginx/nginx.conf or /etc/nginx/conf.d/fastcgi-cache.conf:
fastcgi_cache_path /var/cache/nginx/fastcgi
levels=1:2
keys_zone=PHP_MICRO:128m
max_size=2g
inactive=30m
use_temp_path=off;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
Three parameters here matter most:
keys_zone=PHP_MICRO:128mallocates 128 MB of shared memory for cache keys and metadata. One megabyte indexes roughly 8,000 keys, so 128 MB covers about a million URLs. Don't burn 2 GB on an 8 GB node, and don't starve it at 10 MB when crawlers sweep paginated archives.use_temp_path=offwrites temporary files directly inside/var/cache/nginx/fastcgiinstead of staging them in/var/lib/nginx/fastcgi, avoiding cross-mount copies and keeping commits as atomicrename()calls.inactive=30mlets the cache manager purge URLs untouched for thirty minutes regardless of TTL, keeping disk usage honest during bot sweeps.
Plenty of tutorials insist you mount /var/cache/nginx/fastcgi on tmpfs. On modern Linux servers with NVMe disks, skip tmpfs unless cloud storage IOPS visibly throttle. Hot cache files on ext4 or XFS already sit in Linux page cache at RAM speed. Under memory pressure, the kernel drops clean page cache safely, whereas an oversized tmpfs pins real RAM and invites the OOM killer straight onto PHP-FPM.
Stopping Cache Stampedes With Stale Background Refreshes
A plain ten-second cache handles steady load, then breaks the millisecond a hot key expires. Picture a trending product page taking 150 requests per second. At second 10.001, the entry turns stale. If PHP-FPM needs 120ms to rebuild that page, eighteen concurrent requests punch through at once, run identical database queries, saturate your workers, and trigger cascading 502 errors.
Five directives stop both cold misses and warm-expiry stampedes:
fastcgi_cache_lock on;
fastcgi_cache_lock_age 5s;
fastcgi_cache_lock_timeout 5s;
fastcgi_cache_use_stale error timeout invalid_header updating http_500 http_503;
fastcgi_cache_background_update on;
On a cold miss, fastcgi_cache_lock on sends only the first request to PHP-FPM while peers wait up to five seconds for that entry to land. On warm expiry, fastcgi_cache_use_stale updating paired with fastcgi_cache_background_update on does the real work. The first client hitting an expired key gets the slightly stale HTML in under a millisecond (logged as STALE), while Nginx fires one asynchronous subrequest to PHP-FPM in the background. Everyone else arriving during that 120ms rebuild also gets the stale response immediately. PHP-FPM renders once instead of eighteen times.
Side benefit: if a database failover or bad deploy causes PHP-FPM to time out or return a 500,fastcgi_cache_use_stalekeeps serving the last known good anonymous HTML for up to theinactivewindow, buying your team minutes before visitors even notice.
Bypassing Logged-In Sessions Without Leaking Private HTML
Many guides pile four or five if blocks inside location to compute $skip_cache. That pattern is brittle, ugly in git diffs, and invites classic Nginx if-in-location quirks. Put your bypass rules in clean map blocks inside http instead—maps evaluate lazily once per request and stay dead simple to audit:
map $request_method $skip_by_method {
default 1;
GET 0;
HEAD 0;
}
map $request_uri $skip_by_uri {
default 0;
"~*^/wp-admin" 1;
"~*^/wp-login.php" 1;
"~*^/cart" 1;
"~*^/checkout" 1;
"~*^/my-account" 1;
"~*^/api/" 1;
"~*xmlrpc.php" 1;
}
map $http_cookie $skip_by_cookie {
default 0;
"~*wordpress_logged_in_" 1;
"~*comment_author_" 1;
"~*woocommerce_items_in_cart" 1;
"~*woocommerce_cart_hash" 1;
"~*wp_woocommerce_session_" 1;
"~*PHPSESSID" 1;
"~*laravel_session" 1;
}
map "$skip_by_method:$skip_by_uri:$skip_by_cookie" $skip_cache {
default 1;
"0:0:0" 0;
}
Notice the fail-closed posture on that final map. Only when the request is a GET or HEAD, avoids sensitive URI prefixes, and carries zero session or cart cookies does $skip_cache become 0. Anything unexpected defaults to 1 and passes straight to PHP-FPM.
Never Blindly Ignore Set-Cookie Headers
By default, Nginx refuses to cache any FastCGI response containing Set-Cookie, Cache-Control: private, no-cache, no-store, or a past Expires header. That default behavior is your safety net.
Never paste fastcgi_ignore_headers Cache-Control Expires Set-Cookie; into production because your cache header stays stuck on MISS. If a PHP script starts a session and emits Set-Cookie: PHPSESSID=..., telling Nginx to ignore Set-Cookie stores that response—cookie header included—and hands the identical session ID to the next hundred strangers. That is instant session hijacking via cache poisoning.
When public pages refuse to cache, check upstream headers first. Nine times out of ten, a legacy plugin or middleware calls session_start() unconditionally on anonymous requests, forcing PHP to emit Cache-Control: no-store, no-cache alongside a fresh session cookie. Fix the PHP app so anonymous reads stay stateless, and always let Nginx respect Set-Cookie.
Putting the PHP Location Block Together
With the maps and cache zone declared in http, the PHP handler inside your server block stays tight:
location ~ \.php$ {
try_files $uri =404;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
fastcgi_cache PHP_MICRO;
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
fastcgi_cache_valid 200 15s;
fastcgi_cache_valid 301 302 5m;
fastcgi_cache_valid 404 1m;
fastcgi_cache_lock on;
fastcgi_cache_lock_age 5s;
fastcgi_cache_lock_timeout 5s;
fastcgi_cache_use_stale error timeout invalid_header updating http_500 http_503;
fastcgi_cache_background_update on;
add_header X-FastCGI-Cache $upstream_cache_status always;
}
Wire $skip_cache to both fastcgi_cache_bypass and fastcgi_no_cache. Setting only one is a classic bug: fastcgi_cache_bypass stops Nginx from serving a cached file, while fastcgi_no_cache stops Nginx from saving the upstream response. You need both.
Production Numbers and Re-Sizing PHP-FPM
On an 8-vCPU, 16 GB Debian server running PHP 8.3 FPM behind Nginx 1.26, we rolled this 15-second microcache onto a storefront averaging 310 requests per second—89% anonymous GET traffic and 11% logged-in accounts, cart writes, and webhooks. Before caching, PHP-FPM averaged 81% total host CPU (6.5 cores pinned), p95 TTFB sat at 390ms, and crawler bursts routinely logged server reached pm.max_children.
Ten minutes after reloading Nginx with fastcgi_cache_use_stale updating and fastcgi_cache_background_update on:
- PHP-FPM CPU dropped from 81% to 14.5%—an 82% drop in backend CPU burn.
- Nginx worker CPU ticked up from 4% to 6.8%.
- Anonymous p95 TTFB fell from 390ms to 11ms.
- Zero
pm.max_childrenwarnings fired during two subsequent traffic spikes.
Once 85% to 90% of traffic stops touching PHP-FPM, trim your worker pool to match reality. Leaving sixty idle PHP children parked in RAM for anonymous requests that Nginx now serves wastes gigabytes of memory. Size the pool around bypass concurrency instead—logged-in sessions, checkouts, admin saves, and background refreshes. Spending five minutes estimating required PHP workers under cache bypass alongside dynamic versus static PHP-FPM pool modes usually frees 2 GB to 4 GB of RAM you can hand back to MariaDB or Linux page cache.
Pre-Flight Verification Checklist
Never assume a cache config is safe just because nginx -t passes. Run three quick header checks against staging, then immediately after reloading production:
# 1. Cold anonymous request should return MISS
curl -sI https://example.com/catalog/widgets/
# 2. Immediate repeat should return HIT
curl -sI https://example.com/catalog/widgets/
# 3. Authenticated cookie must return BYPASS
curl -sI -H "Cookie: PHPSESSID=verify999" https://example.com/catalog/widgets/
A healthy cached response looks like this:
HTTP/2 200
server: nginx/1.26.2
date: Tue, 01 Dec 2026 09:14:22 GMT
content-type: text/html; charset=UTF-8
x-fastcgi-cache: HIT
- Verify zero
set-cookieheaders appear on anyHITorSTALEresponse. If one appears, disable caching immediately and inspect your upstream PHP code. - Confirm the Nginx worker user (
www-dataornginx) owns/var/cache/nginx/fastcgi, or every request silently degrades toMISSwhileerror.logfills with permission errors. - Log
$upstream_cache_statusin your access log format. IfMISSdominates popular URLs after an hour, check for tracking query strings likefbclidorutm_sourcefragmentingfastcgi_cache_key. - Walk through a full login, cart update, and logout in a private window. Verify
X-FastCGI-Cache: BYPASSwhile signed in, then confirm anonymous pages flip back toHITafter logout with no leftover account markup.
A fifteen-second microcache sounds tiny on paper, yet it absorbs nearly every burst that kills PHP-FPM boxes in production. Keep your bypass maps fail-closed, never silence Set-Cookie, let fastcgi_cache_use_stale updating smooth out every TTL edge, and your existing server will handle five times the load without adding a single core.
Comments
Post a Comment