Skip to content

Cache upstream responses in Nginx with proxy_cache

A practitioner guide to Nginx proxy_cache: define the cache zone, turn it on for a proxy_pass location, read X-Cache-Status, override upstream cache headers, serve stale on backend errors, and purge without Nginx Plus.

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_pass location and pick a sensible cache key.
  • Expose X-Cache-Status so you can see HIT, MISS, EXPIRED, BYPASS, and STALE.
  • 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 location that already does proxy_pass to 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.
  • curl for 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.

Nginx proxy_cache request path showing HIT served from disk, MISS forwarded to the upstream and stored, plus the stale-while-revalidate branch

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

  1. Declare the cache zone in the http context. This goes in nginx.conf (or a snippet included from it), not inside a server or location block:

    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/nginx is where response files land; levels=1:2 spreads them across two directory tiers so no single directory holds millions of files; keys_zone=api_cache:10m names 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=1g caps disk usage and evicts least-recently-used entries past that; inactive=60m deletes anything not requested for 60 minutes regardless of its own validity; use_temp_path=off writes directly into the cache tree instead of a temp dir on another filesystem, avoiding a cross-device copy on every store.

  2. Create the directory and reload. The worker user (usually nginx or www-data) must own it:

    sudo mkdir -p /var/cache/nginx
    sudo chown -R nginx:nginx /var/cache/nginx
    sudo nginx -t && sudo systemctl reload nginx

    Expected: nginx: configuration file /etc/nginx/nginx.conf test is successful.

  3. Turn caching on in the proxied location. Inside the location that already has proxy_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 10m caches successful and redirect responses for ten minutes; 404 1m caches not-founds briefly so a hammered missing path does not stampede the backend. The add_header ... always line is the single most useful move in this whole guide — it stamps the cache result onto every response, including errors.

  4. Reload and watch the header flip. The first request is a MISS, the second a HIT:

    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
  5. Skip the cache for authenticated requests. Use a map to 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_bypass makes Nginx ignore any cached copy for that request (you get BYPASS); proxy_no_cache stops it from storing the response. Set both, or a logged-in user’s page can end up served to everyone.

  6. Override upstream headers that disable caching. If the backend sends Set-Cookie or Cache-Control: no-cache on 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_headers lets your proxy_cache_valid win over the origin’s headers. Pair it with proxy_hide_header Set-Cookie so you never cache and replay one user’s cookie to another. Only do this for genuinely shared, anonymous responses.

  7. 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_stale serves an expired entry when the upstream errors, times out, or is already being refreshed — visitors see STALE instead of a 502. proxy_cache_background_update on refreshes the entry in the background so the slow request is not the one that waits. proxy_cache_lock on lets 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 sending Set-Cookie or Cache-Control: no-cache/private. Inspect it directly, bypassing Nginx: curl -sI http://127.0.0.1:8080/api/products against the backend port. If you see those headers on responses that are actually shared, add proxy_ignore_headers Set-Cookie Cache-Control Expires; and re-test. Also check you are not sending a request method other than GET/HEAD — Nginx only caches those unless you set proxy_cache_methods.
  • mkdir or write errors in the log: ... failed (13: Permission denied) while ... /var/cache/nginx. The worker user cannot write the cache tree. Find the user with grep -E '^user' /etc/nginx/nginx.conf, then sudo chown -R <user>:<user> /var/cache/nginx. SELinux systems may also need sudo chcon -Rt httpd_cache_t /var/cache/nginx.
  • Authenticated pages are being cached and leaked. Your bypass rule is not matching. Confirm the map regex actually matches your cookie name (sessionid, PHPSESSID, whatever your app uses), and that both proxy_cache_bypass and proxy_no_cache reference it. Add proxy_hide_header Set-Cookie for the shared responses so a cookie can never be stored.
  • Stale content after a deploy. A cached entry lives until proxy_cache_valid expires. 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-Status header is missing. The add_header is in the wrong context or being shadowed. An add_header in a nested block replaces — not merges with — inherited ones, so if you have add_header in both server and location, the location set wins and must include the cache-status line. Keep always so 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.