Cache HTTP Responses with Nginx Reverse Proxy
Configure Nginx as a caching reverse proxy to cache upstream HTTP responses with TTL zones, cache keys, and conditional purging.
Overview
Put Nginx in front of your application and it can cache upstream responses on disk — repeated GET requests never reach the backend. The proxy_cache directives cover the whole lifecycle: a shared-memory zone where keys live, on-disk storage for response bodies, TTL rules per status code, and bypass conditions for traffic that must stay fresh.
When to Use This
- API endpoints with cacheable GET responses (product catalogs, search results, static content)
- Reducing load on backend application servers during traffic spikes
- Caching responses from slow upstream services
- Adding a caching layer without touching application code
Prerequisites
- Nginx 1.20+
- A backend application server running on localhost or an internal network
- Sufficient disk space for the cache zone
Solution
1. Define a Cache Zone
In the http block of nginx.conf:
http {
# Define cache zone: path, levels (directory hierarchy), size, max_size, inactive
proxy_cache_path /var/cache/nginx/api
levels=1:2
keys_zone=api_cache:10m
max_size=1g
inactive=60m
use_temp_path=off;
# Another zone for static assets
proxy_cache_path /var/cache/nginx/assets
levels=1:2
keys_zone=asset_cache:50m
max_size=5g
inactive=24h
use_temp_path=off;
}
levels=1:2: Two-level directory hierarchy for cache files (avoids too many files in one directory)keys_zone=api_cache:10m: 10MB of shared memory for keys (roughly 80,000 keys)max_size=1g: Maximum cache size on diskinactive=60m: Remove files not accessed in 60 minutes (even if TTL hasn’t expired)
2. Enable Caching in a Server Block
server {
listen 80;
server_name api.example.com;
location /api/ {
proxy_pass http://backend:3000;
proxy_cache api_cache;
# Cache key: method + host + URI + query string
proxy_cache_key "$request_method$request_uri";
# TTL by response code
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_valid 500 10s; # Cache errors briefly to protect backend
# Add headers showing cache status
add_header X-Cache-Status $upstream_cache_status;
# Don't cache responses with these headers
proxy_no_cache $http_authorization;
proxy_cache_bypass $http_authorization;
}
location /assets/ {
proxy_pass http://backend:3000;
proxy_cache asset_cache;
proxy_cache_key "$request_uri";
proxy_cache_valid 200 24h;
add_header X-Cache-Status $upstream_cache_status;
}
}
3. Conditional Caching
Skip cache for authenticated requests, POST, or specific query params:
server {
listen 80;
server_name api.example.com;
# Skip cache for POST, PUT, DELETE
set $skip_cache 0;
if ($request_method != GET) {
set $skip_cache 1;
}
# Skip cache for authenticated requests
if ($http_authorization) {
set $skip_cache 1;
}
# Skip cache for specific query params
if ($args ~* "no_cache=1") {
set $skip_cache 1;
}
location /api/ {
proxy_pass http://backend:3000;
proxy_cache api_cache;
proxy_cache_key "$request_method$request_uri";
proxy_cache_valid 200 10m;
proxy_no_cache $skip_cache;
proxy_cache_bypass $skip_cache;
add_header X-Cache-Status $upstream_cache_status;
}
}
4. Cache Locking (Prevent Cache Stampede)
When several requests arrive for the same uncached key, Nginx can lock so only one request reaches the backend:
location /api/ {
proxy_pass http://backend:3000;
proxy_cache api_cache;
proxy_cache_key "$request_method$request_uri";
proxy_cache_valid 200 10m;
# Only one request populates the cache
proxy_cache_lock on;
proxy_cache_lock_timeout 5s; # Wait up to 5s for cache fill
proxy_cache_lock_age 30s; # Give up lock after 30s
# Serve stale content while refreshing
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
proxy_cache_revalidate on;
add_header X-Cache-Status $upstream_cache_status;
}
5. Cache Purge (with the ngx_cache_purge module)
Purging requires a third-party module such as ngx_cache_purge (FRiCKLE) or NGINX Plus’s built-in proxy_cache_purge. With it compiled in:
location ~ /purge(/.*) {
allow 127.0.0.1;
allow 10.0.0.0/8;
deny all;
proxy_cache_purge api_cache "$request_method$1$is_args$args";
}
Purge a specific URL:
curl -X GET http://api.example.com/purge/api/products?page=1
# Returns: 200 OK - Purge successful
6. Upstream Cache Control Headers
Nginx respects Cache-Control headers from the backend by default. Override them:
location /api/ {
proxy_pass http://backend:3000;
proxy_cache api_cache;
proxy_cache_key "$request_uri";
# Ignore backend Cache-Control headers
proxy_ignore_headers Cache-Control Expires Set-Cookie;
# Force caching regardless of backend headers
proxy_cache_valid 200 10m;
# Hide backend headers from client
proxy_hide_header Set-Cookie;
proxy_hide_header Cache-Control;
}
How It Works
- On each request Nginx hashes your
proxy_cache_keyvalue (e.g.,$request_method$request_uri) and uses the digest as the file identifier. Identical keys hit the same entry. keys_zonereserves shared memory for the lookup table; the response bodies themselves live on disk underproxy_cache_path.- For TTLs, Nginx first looks at
proxy_cache_validfor the returned status code. ACache-Control: max-agefrom the backend wins unless you strip it withproxy_ignore_headers. $upstream_cache_statusreportsHIT,MISS,BYPASS,EXPIRED,STALE,UPDATING,REVALIDATEDorNONE— always worth logging.- With
proxy_cache_lock on, the first request for a missing key goes upstream and the rest queue behind it for up toproxy_cache_lock_timeout, then get the freshly cached copy.
Two timers govern how long an entry lives, and they do different jobs:
| Directive | Scope | What it does |
|---|---|---|
proxy_cache_valid | per response code | Sets how long a response stays fresh; past that it becomes EXPIRED or STALE |
inactive (on proxy_cache_path) | per cache zone | Drops entries nobody requested within the window, whatever their TTL says |
A response can expire by TTL yet survive on disk until inactive or max_size forces eviction — that’s why a 10-minute cache doesn’t mean 10 minutes of disk usage.
Variants
Cache with Vary Header
Cache different versions of the same URL based on the Accept header:
proxy_cache_key "$request_method$request_uri$http_accept";
Cache with Cookie Awareness
# Cache differently based on user role cookie
proxy_cache_key "$request_method$request_uri$cookie_user_role";
Microcaching (1-Second Cache)
Cache for a very short TTL to absorb traffic bursts:
location /api/ {
proxy_pass http://backend:3000;
proxy_cache api_cache;
proxy_cache_key "$request_method$request_uri";
proxy_cache_valid 200 1s; # Very short TTL
proxy_cache_lock on;
add_header X-Cache-Status $upstream_cache_status;
}
Cache Warming
Pre-populate the cache by fetching URLs after a deployment:
#!/bin/bash
# warm-cache.sh
URLS=(
"https://api.example.com/api/products?page=1"
"https://api.example.com/api/products?page=2"
"https://api.example.com/api/categories"
)
for url in "${URLS[@]}"; do
status=$(curl -s -o /dev/null -w "%{http_code}" "$url")
echo "$url -> $status"
done
Best Practices
- Budget about 8,000 keys per MB of
keys_zoneshared memory — a 100K-entry cache needs roughly 13MB. - Always pair the cache with
proxy_cache_lock, otherwise a hot key expiring can flood the backend with duplicate fetches. proxy_cache_use_staleis cheap insurance: when the upstream errors or times out, clients get an old copy instead of a 5xx.- Log
X-Cache-Status(or grep it from access logs) so you can watch the hit rate instead of guessing. - Keep
inactiveshorter than your longest TTL. It sweeps out files nobody requests, so disk usage reflects real traffic, not configured TTLs. - Authenticated traffic should bypass the cache via
proxy_cache_bypass $http_authorization; a cached personalized response is a data leak waiting to happen.
Common Mistakes
- Caching anything but GET/HEAD. Gate mutations out with
if ($request_method != GET)before they poison the zone. - Leaving
proxy_cache_keyat its default. The default ignores parts of the request, and two different queries can collide into the same entry. - Caching a response that carries
Set-Cookie— you’ve just shared one user’s session with everyone. Strip it withproxy_hide_header Set-Cookieor bypass. - Sizing
keys_zonetoo small. When the table fills, entries get evicted before their TTL; checknginx -Vand your cache stats. - Skipping
proxy_cache_lockand rediscovering the cache stampede the hard way during a traffic spike.
See Also
- Set Up Nginx as an API Gateway — routing, rate limiting and TLS on the same layer
- CDN Cache Invalidation Strategies — invalidation patterns that complement
proxy_cache_purge - Complete Guide to CDN Caching Strategy — deeper treatment of TTLs, vary and edge rules
- Companion code — runnable
nginx.conf+ Docker Compose setup - ngx_http_proxy_module — proxy_cache directives — official reference
- ngx_cache_purge module — third-party purge support
Frequently Asked Questions
How much disk space does the Nginx cache use?
At most max_size per zone. When the zone fills, a background cache manager process evicts the least recently used files to stay under the cap.
Can I cache HTTPS responses?
Yes. Nginx terminates TLS and proxies to the backend over plain HTTP, so the cache layer only ever sees the decrypted response.
How do I purge the entire cache?
Wipe the directory: rm -rf /var/cache/nginx/api/* — Nginx rebuilds on subsequent requests. For surgical purges of a single URL, use proxy_cache_purge as shown above.
Does Nginx cache compressed (gzip) responses?
Nginx caches the uncompressed response from the backend and compresses per request when gzip on is enabled. To cache compressed bodies, enable gzip_proxied and have the backend send pre-compressed content.
What is microcaching?
A strategy with a very short TTL — one to five seconds — that absorbs bursts by serving cached copies briefly. Backend load drops during spikes without serving stale data for long.
Does the open-source Nginx build support cache purging?
Not by default — you need the third-party ngx_cache_purge module compiled in, or NGINX Plus which ships proxy_cache_purge natively. Without either you're limited to rm -rf on the cache directory or keeping TTLs short.
Why do I get cache hits for the wrong URL?
Usually a proxy_cache_key that doesn't include everything that varies the response — query string, Accept header, or cookies. Check the key with a debug add_header X-Cache-Key $request_uri; and widen it until misses happen where they should.
How do I cache only specific response codes?
Use proxy_cache_valid with explicit status codes: proxy_cache_valid 200 302 10m; caches only 200 and 302 responses for 10 minutes. Codes you don't list aren't cached at all.
What does $upstream_cache_status tell me?
Whether the response came from cache or origin: HIT (served from cache), MISS (fetched from origin), EXPIRED (entry expired, refetched), BYPASS (cache skipped), REVALIDATED (stale but still valid). Add it as a response header to debug cache behavior.
Can I cache responses per user?
Only by including a user identifier in proxy_cache_key — a cookie, for instance. For most setups it's safer to skip cache for authenticated requests entirely, since a misconfigured per-user key can leak one user's response to another.
Related Resources
Configure Nginx as a Reverse Proxy and API Gateway
How to use Nginx as a reverse proxy for backend services, implement load balancing, SSL termination, and rate limiting for production API gateways
RecipeCache Function Results with Redis and TTL in Python
Build a Python decorator that caches function return values in Redis with configurable TTL, key generation, and cache invalidation
RecipeCDN Cache Invalidation Strategies and Patterns
Implement CDN cache invalidation using purge APIs, surrogate keys, tag-based invalidation, and versioned URLs to keep content fresh
RecipeImplement Redis Cache Invalidation in Node.js
Invalidate Redis cache entries in Node.js with TTL expiry, explicit deletion, pattern-based clearing, and pub/sub-based distributed invalidation.
RecipeCache HTTP Responses with httpx and CacheControl in Python
Cache HTTP responses in Python using httpx with CacheControl for HTTP-compliant caching, ETag handling, and conditional requests.