proxy_cache lets Nginx remember a response from a proxy_pass backend and serve the next identical request straight from disk without touching the upstream at all. You declare a cache zone once in the http context with proxy_cache_path, switch it on inside the location that proxies to your app, and add one debugging header so every response tells you whether it was a HIT or a MISS. Done right, an app server that manages tens of requests per second can sit behind an Nginx that serves thousands, and it keeps answering even while the backend is restarting. This is distinct from FastCGI caching, which caches PHP-FPM output over a fastcgi_pass socket. If your responses come from a proxy_pass upstream — a Node or Python app, an internal API, an object-storage origin — proxy_cache is the directive family you want.
What you’ll accomplish
- Define a named cache zone on disk with a shared-memory key index and a size cap.
- Turn caching on for one
proxy_passlocation and pick a sensible cache key. - Expose
X-Cache-Statusso you can seeHIT,MISS,EXPIRED,BYPASS, andSTALE. - Skip the cache for authenticated traffic, and override upstream headers that silently disable it.
- Keep serving cached content while the backend is down, and purge entries without Nginx Plus.
Prerequisites
- Nginx 1.20 or newer (
nginx -v). Every directive here ships in open-source Nginx except where noted. - A working reverse proxy — a
locationthat already doesproxy_passto an upstream. If you do not have one yet, start with a plain reverse proxy setup and add caching afterward. - Write access to a cache directory (this guide uses
/var/cache/nginx) owned by the Nginx worker user. curlfor inspecting response headers, and the ability to reload Nginx (nginx -t && systemctl reload nginx).
How it works
Nginx computes a cache key for each request. If a fresh entry exists, it serves the stored bytes from disk and never contacts the upstream — that is a HIT. If nothing matches (or the entry is stale), it forwards the request via proxy_pass, stores the response according to your validity rules, and returns it — a MISS. The key-to-file map lives in a shared-memory zone so any worker can find an entry; the response bodies live as files on disk.
The subtle part is what Nginx refuses to cache. By default it honours the upstream’s Cache-Control, Expires, and Set-Cookie headers, so a backend that sends Set-Cookie on every response makes everything a MISS forever. You override that deliberately, and you decide which requests bypass the cache entirely.
Step-by-step
-
Declare the cache zone in the
httpcontext. This goes innginx.conf(or a snippet included from it), not inside aserverorlocationblock:proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:10m max_size=1g inactive=60m use_temp_path=off;Each parameter earns its place:
/var/cache/nginxis where response files land;levels=1:2spreads them across two directory tiers so no single directory holds millions of files;keys_zone=api_cache:10mnames the zone (api_cache) and reserves 10 MB of shared memory for keys — roughly 80,000 entries per megabyte, so about 800,000 keys here;max_size=1gcaps disk usage and evicts least-recently-used entries past that;inactive=60mdeletes anything not requested for 60 minutes regardless of its own validity;use_temp_path=offwrites directly into the cache tree instead of a temp dir on another filesystem, avoiding a cross-device copy on every store. -
Create the directory and reload. The worker user (usually
nginxorwww-data) must own it:sudo mkdir -p /var/cache/nginx sudo chown -R nginx:nginx /var/cache/nginx sudo nginx -t && sudo systemctl reload nginxExpected:
nginx: configuration file /etc/nginx/nginx.conf test is successful. -
Turn caching on in the proxied location. Inside the
locationthat already hasproxy_pass, reference the zone and set validity per status code:location /api/ { proxy_pass http://backend; proxy_cache api_cache; proxy_cache_key "$scheme$request_method$host$request_uri"; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; add_header X-Cache-Status $upstream_cache_status always; }proxy_cache_valid 200 302 10mcaches successful and redirect responses for ten minutes;404 1mcaches not-founds briefly so a hammered missing path does not stampede the backend. Theadd_header ... alwaysline is the single most useful move in this whole guide — it stamps the cache result onto every response, including errors. -
Reload and watch the header flip. The first request is a
MISS, the second aHIT:curl -sI https://example.com/api/products | grep -i x-cache-status # X-Cache-Status: MISS curl -sI https://example.com/api/products | grep -i x-cache-status # X-Cache-Status: HIT -
Skip the cache for authenticated requests. Use a
mapto flag requests that carry a session cookie, then bypass reads and forbid writes:map $http_cookie $skip_cache { default 0; "~*sessionid=" 1; } location /api/ { proxy_pass http://backend; proxy_cache api_cache; proxy_cache_bypass $skip_cache; proxy_no_cache $skip_cache; add_header X-Cache-Status $upstream_cache_status always; }proxy_cache_bypassmakes Nginx ignore any cached copy for that request (you getBYPASS);proxy_no_cachestops it from storing the response. Set both, or a logged-in user’s page can end up served to everyone. -
Override upstream headers that disable caching. If the backend sends
Set-CookieorCache-Control: no-cacheon responses you know are safe to cache, tell Nginx to ignore those headers:location /api/ { proxy_pass http://backend; proxy_cache api_cache; proxy_ignore_headers Set-Cookie Cache-Control Expires; proxy_hide_header Set-Cookie; proxy_cache_valid 200 10m; add_header X-Cache-Status $upstream_cache_status always; }proxy_ignore_headerslets yourproxy_cache_validwin over the origin’s headers. Pair it withproxy_hide_header Set-Cookieso you never cache and replay one user’s cookie to another. Only do this for genuinely shared, anonymous responses. -
Serve stale content while the backend is in trouble. This is where caching pays for itself during an incident:
location /api/ { proxy_pass http://backend; proxy_cache api_cache; proxy_cache_valid 200 10m; proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504; proxy_cache_background_update on; proxy_cache_lock on; add_header X-Cache-Status $upstream_cache_status always; }proxy_cache_use_staleserves an expired entry when the upstream errors, times out, or is already being refreshed — visitors seeSTALEinstead of a 502.proxy_cache_background_update onrefreshes the entry in the background so the slow request is not the one that waits.proxy_cache_lock onlets only one request populate a given key at a time, so a cold cache under load does not send a thundering herd of identical requests to the backend.
Validate it works
Confirm the zone is loaded, the files exist, and the header behaves:
sudo nginx -T | grep -E 'proxy_cache_path|proxy_cache '
ls -R /var/cache/nginx | head
curl -sI https://example.com/api/products | grep -i x-cache-status
The first curl after a reload shows MISS, the second HIT. Force a stale scenario by stopping the backend and requesting a previously cached path — with proxy_cache_use_stale set you should still get a 200 and X-Cache-Status: STALE rather than a 502. To see an entry on disk, hash the key: the file lives under /var/cache/nginx/<last char>/<two chars before that>/<full md5>.
Troubleshooting
- Everything is
MISS, nothing ever caches. The upstream is almost certainly sendingSet-CookieorCache-Control: no-cache/private. Inspect it directly, bypassing Nginx:curl -sI http://127.0.0.1:8080/api/productsagainst the backend port. If you see those headers on responses that are actually shared, addproxy_ignore_headers Set-Cookie Cache-Control Expires;and re-test. Also check you are not sending a request method other thanGET/HEAD— Nginx only caches those unless you setproxy_cache_methods. mkdiror write errors in the log:... failed (13: Permission denied) while ... /var/cache/nginx. The worker user cannot write the cache tree. Find the user withgrep -E '^user' /etc/nginx/nginx.conf, thensudo chown -R <user>:<user> /var/cache/nginx. SELinux systems may also needsudo chcon -Rt httpd_cache_t /var/cache/nginx.- Authenticated pages are being cached and leaked. Your bypass rule is not matching. Confirm the
mapregex actually matches your cookie name (sessionid,PHPSESSID, whatever your app uses), and that bothproxy_cache_bypassandproxy_no_cachereference it. Addproxy_hide_header Set-Cookiefor the shared responses so a cookie can never be stored. - Stale content after a deploy. A cached entry lives until
proxy_cache_validexpires. Either lower the validity for volatile paths, add a version segment to the key (see below), or delete the cache files and reload. There is no built-in “flush now” in open-source Nginx. X-Cache-Statusheader is missing. Theadd_headeris in the wrong context or being shadowed. Anadd_headerin a nested block replaces — not merges with — inherited ones, so if you haveadd_headerin bothserverandlocation, thelocationset wins and must include the cache-status line. Keepalwaysso it appears on error responses too.
Cache purging without Nginx Plus
The proxy_cache_purge directive is not in open-source Nginx — it is a commercial Nginx Plus feature, and no amount of config enables it in the free build. Be honest with yourself about that before you design around it. In open-source Nginx you have two practical options. First, delete files: everything under proxy_cache_path is disposable, so find /var/cache/nginx -type f -delete clears the lot, and a reload is not even required. To target one URL you must reproduce its key hash — printf '%s' 'httpsGETexample.com/api/products' | md5sum — and delete that specific file. Second, and usually cleaner, bust the cache through the key: include a deploy version or content hash in proxy_cache_key (for example add $arg_v or a variable set from a header), and changing it makes every old entry unreachable without deleting anything. The third-party ngx_cache_purge module adds a purge directive to open-source builds, but it requires recompiling Nginx with the module, so treat it as a build decision, not a runtime toggle.
When this is the wrong approach
Do not reach for proxy_cache when responses are genuinely per-user — a dashboard, a cart, anything keyed to a session — because the safe configuration ends up bypassing the cache on every request anyway, and you have added complexity for no hit rate. It is also the wrong layer when the upstream already sets correct, honourable Cache-Control headers and a CDN in front of Nginx is doing the caching; adding a second cache tier just multiplies your stale-content debugging. And if you need instant, surgical invalidation of individual objects on a free build, the file-deletion dance is fragile enough that a small dedicated cache such as Varnish, or moving that concern to a CDN with a purge API, will hurt less. For static files that never vary by upstream state, plain static asset caching with far-future headers is simpler than a proxy cache. Full directive reference lives in the Nginx proxy module docs.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.