Nginx · The edge of your stack

How do you configure proxy caching in Nginx?

Mediumproxy cachecache keyupstreamUpdated Oct 2026
Quiz this track

Short answer

Define a proxy_cache_path, enable proxy_cache in a location, choose a cache key and TTLs, and expose $upstream_cache_status. Only cache responses that are safe to share.

Proxy caching stores upstream responses on disk. It reduces backend load and improves latency for repeated requests, but the cache key and cacheability rules decide whether it is safe and effective.

nginx
proxy_cache_path /var/cache/nginx/api levels=1:2 keys_zone=api_cache:10m max_size=1g inactive=10m use_temp_path=off;

server {
    location /api/ {
        proxy_cache api_cache;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        proxy_cache_valid 200 301 302 5m;
        proxy_cache_valid 404 1m;
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
        proxy_cache_background_update on;
        proxy_cache_lock on;
        proxy_cache_bypass $http_authorization $cookie_session;
        proxy_no_cache $http_authorization $cookie_session;
        add_header X-Cache-Status $upstream_cache_status always;
        proxy_pass http://backend;
    }
}

What to think about

  • Cache only GET and HEAD responses unless you have a very specific reason
  • Respect Cache-Control unless you intentionally override it
  • Include every dimension that changes the response in the cache key or in Vary
  • proxy_cache_lock collapses concurrent misses into one upstream request
  • Use stale-while-revalidate behavior to survive brief backend failures
Caching a personalized response is a security incident, not just a correctness bug. Bypass the cache for authenticated or session-bearing requests, and never key solely on a URL that ignores user identity.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What does $upstream_cache_status tell you?
  2. 2Why can caching authenticated responses be dangerous?
  3. 3How does proxy_cache_lock help during a cache stampede?
  4. 4What is the difference between proxy_cache_bypass and proxy_no_cache?

Say it in the interview

I define a disk cache with a bounded zone and size, enable it in a location and set a cache key that includes every dimension that changes the response. I expose X-Cache-Status so I can verify hits and misses. I bypass the cache for authenticated or session-bearing traffic, and I use locking and stale responses to protect the backend during misses or outages.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Nginx mock interview and get scored feedback on depth, clarity and confidence.