Web servers and networking · Intermediate · 16 min
Cache responses from your app with Nginx proxy_cache
By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · Nginx 1.30.8 · Node.js 26.13.1
You will put an Nginx 1.30 cache in front of a small Node.js app, read HIT, MISS, EXPIRED, STALE and BYPASS from a response header, keep pages up while the app is down, and clear entries by hand.
On this page
Most pages an app renders are the same for every visitor for at least a few seconds. If Nginx keeps a copy, it can answer the next thousand requests itself, and the app only does the work once. That copy is a proxy cache. It also lets Nginx keep serving a page while the app restarts or falls over, which is often the bigger win on a single small server.
In this tutorial you will run a Node.js app that counts every request it handles, put an Nginx cache in front of it, and watch the count to prove what the cache is doing. You will add a header that shows the cache status of each response, let the app decide how long things are cached, serve stale pages when the app is down, stop a burst of requests from all reaching the app, skip the cache for signed-in users, and clear entries by hand.
This is about Nginx storing your app's responses. What the app sends in Cache-Control is covered in /tutorials/set-caching-headers-for-api-responses, and the two work together. A shorter time to first byte matters most to visitors on slow mobile connections and prepaid data, where every round trip to a busy app is felt.
Step 1 · Run an app that counts its requests
Install Nginx 1.30 from nginx.org and Node.js 26 first, as in /tutorials/nginx-reverse-proxy-for-a-node-app.
The app has four pages, and each one behaves differently so you can see a different part of the cache:
/timesends no caching header, so Nginx's own rule decides./newssendsCache-Control: public, max-age=5, a short lifetime the app chooses./accountsendsCache-Control: private, no-store, as a page with personal data would./reporttakes two seconds to build and may be cached for a minute.
Every page returns how many times the app has handled it. /stats returns all the counts and is never cached.
mkdir -p ~/cache-demo
cat > ~/cache-demo/server.js <<'JS'
const http = require('node:http');
const hits = {};
const pages = {
'/time': { cacheControl: null, delayMs: 0 },
'/news': { cacheControl: 'public, max-age=5', delayMs: 0 },
'/account': { cacheControl: 'private, no-store', delayMs: 0 },
'/report': { cacheControl: 'public, max-age=60', delayMs: 2000 },
};
http.createServer((req, res) => {
const path = new URL(req.url, 'http://localhost').pathname;
if (path === '/stats') {
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify(hits) + '\n');
return;
}
const page = pages[path];
if (!page) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('not found\n');
return;
}
hits[path] = (hits[path] || 0) + 1;
const body = JSON.stringify({ path, hits: hits[path], builtAt: new Date().toISOString() }) + '\n';
const headers = { 'Content-Type': 'application/json' };
if (page.cacheControl) headers['Cache-Control'] = page.cacheControl;
setTimeout(() => {
res.writeHead(200, headers);
res.end(body);
}, page.delayMs);
}).listen(3000, '127.0.0.1', () => {
console.log('app listening on http://127.0.0.1:3000');
});
JSStart it in your second terminal and leave it running:
node ~/cache-demo/server.jsIt prints app listening on http://127.0.0.1:3000. For a long-lived app you would run it under systemd, as the reverse proxy tutorial shows; a terminal is enough here.
Check it worked
In the first terminal, ask the app for /time twice, without Nginx:
curl -s http://127.0.0.1:3000/time
curl -s http://127.0.0.1:3000/timeThe first line shows "hits":1 and the second "hits":2. Every direct request reaches the app.
Step 2 · Create a cache and proxy through it
A proxy cache needs two things: a place on disk with a shared memory zone for its index, declared once with proxy_cache_path at the http level, and a proxy_cache line in each location that uses it. Files in /etc/nginx/conf.d/ are included at the http level, so both can live in one file.
This server block listens on port 8080 so it does not disturb any site you already serve on port 80. On a real site you would add these lines to that site's server block instead.
sudo tee /etc/nginx/conf.d/cache-demo.conf > /dev/null <<'CONF'
proxy_cache_path /var/cache/nginx/app levels=1:2 keys_zone=app_cache:10m
max_size=1g inactive=60m use_temp_path=off;
server {
listen 8080;
server_name _;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache app_cache;
proxy_cache_key $scheme$host$request_uri;
proxy_cache_valid 200 10s;
add_header X-Cache-Status $upstream_cache_status always;
}
}
CONF
sudo nginx -tApply it:
sudo systemctl reload nginxWhat each part does:
/var/cache/nginx/appis where the cached responses are stored as files. Nginx creates it.levels=1:2spreads the files over two levels of subfolders so no single folder holds thousands of files.keys_zone=app_cache:10mnames the cache and gives its index 10 MB of shared memory. The Nginx docs put one megabyte at about 8,000 keys, so this holds around 80,000 cached URLs.max_size=1gcaps the files on disk. When the cache grows past it, Nginx removes the least recently used entries.inactive=60mremoves an entry nobody has asked for in 60 minutes, whether or not it is still fresh. The default is 10 minutes.use_temp_path=offwrites responses straight into the cache folder rather than copying them across from Nginx's temporary folder.proxy_cache_keyis what makes two requests "the same". Including$hostkeeps two sites that share one cache apart.proxy_cache_valid 200 10skeeps successful responses for 10 seconds when the app does not say otherwise. Other status codes are not cached unless you list them.add_header X-Cache-Status $upstream_cache_status alwaysshows the cache result on every response, including errors. Anadd_headerinside a location replaces anyadd_headerlines it would otherwise inherit from the server block, so repeat your security headers here if you have them.
Check it worked
Ask Nginx for /time twice. The grep keeps the status header and the body line:
curl -s -i http://localhost:8080/time | grep -iE '^x-cache-status|hits'
curl -s -i http://localhost:8080/time | grep -iE '^x-cache-status|hits'The first response shows X-Cache-Status: MISS and "hits":3: Nginx had no copy, asked the app, and stored the answer. The second shows X-Cache-Status: HIT and the same "hits":3, because Nginx answered from its copy and the app never saw the request. The cache file is now on disk:
sudo find /var/cache/nginx/app -type fOne file is listed, with a long hexadecimal name, two folders deep.
Step 3 · Let the app's Cache-Control decide
Nginx reads the app's response headers before its own rule. If the response has Cache-Control: max-age=N (or an Expires header), that lifetime wins over proxy_cache_valid. If it says private, no-store or no-cache, or sets a cookie with Set-Cookie, Nginx does not store it at all. This means the app, which knows its data, stays in charge, and the Nginx rule is only a fallback.
Try /news, which the app says may be cached for 5 seconds:
curl -s -i http://localhost:8080/news | grep -i '^x-cache-status'
curl -s -i http://localhost:8080/news | grep -i '^x-cache-status'
sleep 6
curl -s -i http://localhost:8080/news | grep -iE '^x-cache-status|hits'You see MISS, then HIT, then, after the 6-second pause, EXPIRED with "hits":2. EXPIRED means Nginx had a copy but it was past its lifetime, so it fetched a fresh one from the app and stored that.
Now try /account, which is marked private:
curl -s -i http://localhost:8080/account | grep -iE '^x-cache-status|hits'
curl -s -i http://localhost:8080/account | grep -iE '^x-cache-status|hits'Check it worked
Both responses show X-Cache-Status: MISS, and the hit count goes from 1 to 2. Nginx looked for a copy, found none, and did not store the app's answer because of private, no-store. Confirm with the app's own counts:
curl -s http://127.0.0.1:3000/statsThe output includes "/account":2. Every request for a private page reached the app.
Be careful with proxy_ignore_headers. It can tell Nginx to ignore Cache-Control and Set-Cookie, and that is how one visitor's page, with their name and session cookie, ends up served to everyone else.
Step 4 · Serve stale pages when the app is slow or down
When a cached copy has expired and the app cannot answer, Nginx returns an error by default, even though it has a copy that is only a few seconds old. proxy_cache_use_stale lets it send that copy instead. With proxy_cache_background_update, Nginx also stops making visitors wait while it refreshes an expired copy: it sends the stale copy at once and fetches the new one in the background.
Rewrite the file with three new lines in the location block:
sudo tee /etc/nginx/conf.d/cache-demo.conf > /dev/null <<'CONF'
proxy_cache_path /var/cache/nginx/app levels=1:2 keys_zone=app_cache:10m
max_size=1g inactive=60m use_temp_path=off;
server {
listen 8080;
server_name _;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache app_cache;
proxy_cache_key $scheme$host$request_uri;
proxy_cache_valid 200 10s;
add_header X-Cache-Status $upstream_cache_status always;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
proxy_read_timeout 10s;
}
}
CONF
sudo nginx -tsudo systemctl reload nginxThe parameters of proxy_cache_use_stale list when a stale copy is allowed: error when Nginx cannot connect, timeout when the app takes longer than proxy_read_timeout, http_5xx when the app answers with that error, and updating while another request is already refreshing the copy. Background updates need updating in the list. An app can also allow this per response with the stale-while-revalidate and stale-if-error parts of Cache-Control, which Nginx honours, but the directive here takes priority.
Now take the app down. Press Ctrl+C in the second terminal.
Wait long enough for the cached /news to expire, then ask for it:
sleep 6
curl -s -i http://localhost:8080/news | grep -iE '^HTTP|^x-cache-status|hits'Check it worked
The response is HTTP/1.1 200 OK with X-Cache-Status: STALE and the old "hits":2 body. The app is down, and visitors still get the page. A URL that was never cached has no copy to fall back on, so it still returns 502 Bad Gateway.
Start the app again in the second terminal:
node ~/cache-demo/server.jsThen ask for /news twice, a second apart:
curl -s -i http://localhost:8080/news | grep -iE '^x-cache-status|hits'
sleep 1
curl -s -i http://localhost:8080/news | grep -iE '^x-cache-status|hits'The first answer is still STALE with the old body, sent without waiting for the app. Behind it, Nginx fetched a fresh copy. The second answer is a HIT with "hits":1, the first request the restarted app has handled.
Stale pages are a trade-off. Use them for pages where being a few seconds or minutes old is harmless, such as articles, listings and product pages, and keep them away from stock levels, balances or anything a visitor acts on.
Step 5 · Stop a burst of requests from all reaching the app
When a popular page is not in the cache yet, say just after a deploy, every request that arrives before the first response is stored goes to the app. For a page that takes two seconds to build, that can be hundreds of requests doing the same work at once. proxy_cache_lock on lets only the first one through. The rest wait for its response to land in the cache and are served from there.
Add two lines under proxy_read_timeout:
sudo tee /etc/nginx/conf.d/cache-demo.conf > /dev/null <<'CONF'
proxy_cache_path /var/cache/nginx/app levels=1:2 keys_zone=app_cache:10m
max_size=1g inactive=60m use_temp_path=off;
server {
listen 8080;
server_name _;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache app_cache;
proxy_cache_key $scheme$host$request_uri;
proxy_cache_valid 200 10s;
add_header X-Cache-Status $upstream_cache_status always;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
proxy_read_timeout 10s;
proxy_cache_lock on;
proxy_cache_lock_timeout 5s;
}
}
CONF
sudo nginx -tsudo systemctl reload nginxIf the first request takes longer than proxy_cache_lock_timeout (5 seconds is also the default), the waiting requests go to the app after all, and their responses are not cached. Set it a little above the time your slowest cacheable page takes. The lock covers entries that do not exist yet; for entries that have expired, the updating setting from the last step already keeps the burst away from the app.
Send five requests for the slow /report page at the same moment:
seq 5 | xargs -P 5 -I{} curl -s -o /dev/null -w '%{http_code} ' http://localhost:8080/report
echoxargs -P 5 runs the five curl commands in parallel and returns when all of them have finished. All five print 200, after about two seconds.
Check it worked
Ask the app how many times it built the report:
curl -s http://127.0.0.1:3000/statsThe output includes "/report":1. Five visitors, one build. Without the lock, it would be 5.
Step 6 · Skip the cache for signed-in users
A signed-in page often looks shared, with the same URL for everyone, but shows a name, a basket or an account menu. If such a page is cached, the next visitor sees someone else's details. The safe rule: when the request carries a session cookie or an Authorization header, neither read from the cache nor write to it.
proxy_cache_bypass skips reading the cache, and proxy_no_cache skips storing the response. Each takes a list of values and acts when any of them is set to something other than empty or 0. $cookie_session is the value of a cookie called session. Replace session with the name of your app's session cookie.
Add the two lines at the end of the location block:
sudo tee /etc/nginx/conf.d/cache-demo.conf > /dev/null <<'CONF'
proxy_cache_path /var/cache/nginx/app levels=1:2 keys_zone=app_cache:10m
max_size=1g inactive=60m use_temp_path=off;
server {
listen 8080;
server_name _;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache app_cache;
proxy_cache_key $scheme$host$request_uri;
proxy_cache_valid 200 10s;
add_header X-Cache-Status $upstream_cache_status always;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
proxy_read_timeout 10s;
proxy_cache_lock on;
proxy_cache_lock_timeout 5s;
proxy_cache_bypass $cookie_session $http_authorization;
proxy_no_cache $cookie_session $http_authorization;
}
}
CONF
sudo nginx -tsudo systemctl reload nginxUse both lines, never just the bypass. With only proxy_cache_bypass, a signed-in user's response skips the cache on the way in but is still stored on the way out, and anonymous visitors are then served it.
Fill the cache as an anonymous visitor, then make two requests with a session cookie:
curl -s http://localhost:8080/time > /dev/null
sleep 1
curl -s -i http://localhost:8080/time | grep -iE '^x-cache-status|hits'
curl -s -i -H 'Cookie: session=demo' http://localhost:8080/time | grep -iE '^x-cache-status|hits'
curl -s -i -H 'Cookie: session=demo' http://localhost:8080/time | grep -iE '^x-cache-status|hits'The anonymous request is a HIT. The two with the cookie show X-Cache-Status: BYPASS, and their hit count goes up each time, because each one reached the app.
Check it worked
Make one more anonymous request:
curl -s -i http://localhost:8080/time | grep -iE '^x-cache-status|hits'It is a HIT with the same hit count as the first anonymous request, not the signed-in ones. The responses for the cookie holder were never stored.
Requests other than GET and HEAD, such as a POST from a form, are never cached by default, so you do not need a rule for them.
Step 7 · Clear cached entries by hand
Sooner or later you publish a fix and do not want to wait for the old copy to expire. Open-source Nginx has no purge command; the proxy_cache_purge directive is only in the commercial NGINX Plus. You can still remove entries, because each one is a file whose name is the MD5 hash of its cache key.
The key here is $scheme$host$request_uri, so /news on localhost has the key httplocalhost/news. With levels=1:2, the file sits in a folder named after the last character of the hash, inside a folder named after the two characters before it. Make sure /news is cached first, then find its file and read the key stored inside it:
curl -s -o /dev/null http://localhost:8080/news
sleep 1
KEY='httplocalhost/news'
HASH=$(printf '%s' "$KEY" | md5sum | cut -d' ' -f1)
FILE="/var/cache/nginx/app/${HASH: -1}/${HASH: -3:2}/$HASH"
sudo grep -a '^KEY:' "$FILE"It prints KEY: httplocalhost/news, which proves you found the right file. Delete it:
sudo rm "$FILE"
curl -s -i http://localhost:8080/news | grep -i '^x-cache-status'Check it worked
The response shows X-Cache-Status: MISS. Nginx treats a missing file as no copy, fetches a fresh response and stores it again.
To empty the whole cache, delete every file under the cache folder. Check the path before you press Enter: this removes everything below it, and a typo in the path deletes other files.
sudo find /var/cache/nginx/app -type f -delete
curl -s -i http://localhost:8080/time | grep -i '^x-cache-status'The next request for any page is a MISS. Nginx's memory index still lists the deleted entries until they pass inactive or max_size pushes them out, which does no harm.
If you clear the cache on every deploy, a shorter lifetime from the app, plus proxy_cache_use_stale updating, is usually the better fix.
Step 8 · Remove the demo
Stop the app with Ctrl+C in the second terminal.
This deletes the demo config, its cache folder and the app. Check that /etc/nginx/conf.d/cache-demo.conf is the demo file before you remove it:
sudo rm /etc/nginx/conf.d/cache-demo.conf
sudo nginx -tsudo systemctl reload nginxsudo rm -rf /var/cache/nginx/app
rm -rf ~/cache-demoCheck it worked
curl -sS http://localhost:8080/ || echo "nothing is listening on port 8080"curl reports that it failed to connect, followed by nothing is listening on port 8080. Your other Nginx sites are untouched.
Next steps
- Decide what the app itself sends in
Cache-Controlwith/tutorials/set-caching-headers-for-api-responses. - Move the cache closer to your visitors with
/tutorials/prepare-your-site-for-a-cdn. - Put the cache in front of several app servers with
/tutorials/load-balance-with-nginx-upstream. - Revisit the proxy headers and systemd unit in
/tutorials/nginx-reverse-proxy-for-a-node-app.
Related tutorials
- Write Nginx location blocks that match what you expectYou will build a practice Nginx 1.30 server where every location block labels its responses, predict which block answers each of twelve URLs, check your answers with curl, and fix the alias, regex-order and proxy_pass mistakes that catch most people out.
- Write a server firewall with nftablesYou will write one /etc/nftables.conf with a default-drop input chain, rate-limited SSH, named address sets, counters and logging, and load it over SSH behind a timer that undoes it if you lose your connection.
- Watch a TCP connection open and close with tcpdumpYou will capture a curl request to a local web server with tcpdump on Ubuntu 26.04, read its handshake, data and teardown line by line, see the reset a closed port sends, and save, filter and rotate captures as pcap files.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials