Skip to content

HTTP caching headers: Cache-Control, ETag, and Last-Modified

A practitioner guide to http caching headers: what Cache-Control, ETag and Last-Modified actually do, the right policy per asset type in nginx and Apache, and how to prove a 304 with curl.

Caching headers answer two separate questions, and most confusion comes from mixing them up. Cache-Control answers “may this be reused, by whom, and for how long?” — it is the policy. ETag and Last-Modified answer “is the copy I already have still good?” — they are the cheap way to check without re-downloading the body. Get the first one right and requests never leave the machine; get the second one right and the ones that do leave come back as an empty 304 Not Modified instead of a megabyte of JavaScript. The whole thing collapses into a rule that is easier than the specification makes it look: if the filename changes when the content changes, cache it for a year; if it does not, cache it briefly or not at all.

What you’ll accomplish

  • Read any response’s caching behaviour straight off its headers, and say what a browser and a CDN will each do with it.
  • Write a per-asset-type policy you can defend in review: content-hashed assets forever, HTML revalidated, personalized responses never stored.
  • Configure that policy in both nginx and Apache, including the ETag settings that matter behind a load balancer.
  • Prove it with curl — a 200 on first fetch, a 304 on conditional revalidation — instead of guessing from a devtools column.
  • Tell no-cache from no-store, and max-age from s-maxage, without looking them up again.

Prerequisites

  • A server whose response headers you control. This guide shows nginx (1.18+) and Apache (2.4) directives; any origin works if you can set headers on it.
  • curl 7.x or 8.x. Every example uses -I (headers only) so nothing large gets downloaded.
  • Browser devtools, for the Network tab’s Size column — the one place “served from cache” is visible without a request.
  • A note before you start: if there is a CDN in front of your origin, it may rewrite what you set. Cloudflare, Fastly, and CloudFront all have their own TTL settings that can override or ignore origin Cache-Control. Always verify at the edge as well as at the origin — the last step of this guide shows how to check both.

How it works

A cached response has two states. It is fresh while its age is below its lifetime, and stale afterwards. Age is how many seconds have passed since the origin generated it; lifetime comes from max-age (or the older Expires header). A fresh response is reused with no network request at all — that is the entire performance win, and it is why devtools reports 0 ms.

Once a response goes stale, the cache does not throw it away. It revalidates: it re-sends the request with a validator attached, and the origin answers either 304 Not Modified (an empty body meaning “your copy is fine, reset its age”) or 200 OK with fresh bytes. A 304 still costs a round trip, so it is much slower than a fresh hit — but far cheaper than re-transferring the body.

The validators are ETag and Last-Modified. An ETag is an opaque token the origin computes for a specific version of a resource; the client echoes it back in If-None-Match. Last-Modified is a timestamp; the client echoes it in If-Modified-Since. ETags are more precise: Last-Modified has one-second granularity and cannot distinguish “rebuilt with identical content” from “actually changed”. Serve both — clients prefer the ETag when they have one.

ETags come in two strengths. A strong ETag ("abc123") promises byte-for-byte identity. A weak one (W/"abc123") only promises semantic equivalence. If-None-Match uses weak comparison, so both work for revalidation; range requests need a strong one.

Finally, caches come in two kinds, and the directives split along that line. A private cache belongs to one user (the browser’s disk cache). A shared cache serves many (a CDN, a reverse proxy). private means only the browser may store it. public means a shared cache may too. s-maxage sets a lifetime only shared caches honour, letting you hold something at the edge for a day while browsers keep it for an hour.

Decision path for a cached request: a fresh copy is served from the browser disk cache with no network hop, while a stale copy sends a conditional GET through the shared cache to the origin, returning either 304 Not Modified or 200 OK

Step-by-step

1. Look at what you are actually sending. Before changing anything, read the current headers. -I sends a HEAD request and prints only the response headers:

curl -I https://example.com/assets/app.a3f9c2e1.js
HTTP/2 200
server: nginx/1.24.0
date: Wed, 15 Jul 2026 14:02:11 GMT
content-type: application/javascript
content-length: 148213
last-modified: Mon, 13 Jul 2026 09:31:44 GMT
etag: "6a54b080-242f5"
cache-control: public, max-age=31536000, immutable
accept-ranges: bytes

Header names arrive lowercase over HTTP/2 — that is the protocol, not a misconfiguration. The remaining examples pin --http1.1 so the output stays in the familiar capitalized form.

2. Set the forever policy on content-hashed assets. If your build emits app.a3f9c2e1.js and the hash changes whenever the source does, the URL is a permanent name for those exact bytes. Nothing can go stale, so cache it for the maximum and skip revalidation entirely:

# Content-hashed build output — the filename changes when the bytes change.
location ~* "^/assets/.+\.[0-9a-f]{8,}\.(?:js|css|woff2|png|svg)$" {
    add_header Cache-Control "public, max-age=31536000, immutable" always;
    access_log off;
    try_files $uri =404;
}

31536000 is one year in seconds, the practical ceiling. immutable (RFC 8246) is the part people miss: without it, a browser reload still fires a conditional request for every asset on the page. immutable tells the cache not to bother — the answer cannot have changed.

3. Keep HTML revalidating so deploys land. The HTML document is what points at the hashed assets. If it is cached long, a user keeps loading the old document, which keeps referencing the old asset names, and your deploy silently never reaches them:

# The entry document. Stored, but revalidated on every load.
location = /index.html {
    add_header Cache-Control "no-cache" always;
}

4. Learn the one distinction that matters: no-cache is not no-store. The names are backwards from intuition and it causes real outages:

  • no-cache — do store the response, but revalidate with the origin before every reuse. You still get 304s, so it is cheap. This is what you want for HTML.
  • no-store — never write it down at all, in any cache, on disk or in memory. There is nothing to revalidate. Use it for personalized or sensitive responses only.

Reaching for no-store on HTML because you wanted “always fresh” throws away every 304 and re-downloads the full document on each load. no-cache already gives you “always fresh”.

5. Split browser and edge lifetimes with s-maxage. For static files that keep the same name across deploys — a logo, a favicon — you cannot cache forever, but you can cap the damage while still getting edge hits:

# Unhashed static files: short in browsers, longer at the edge.
location /static/ {
    add_header Cache-Control "public, max-age=3600, s-maxage=86400, stale-while-revalidate=60" always;
}

Browsers use max-age=3600; shared caches use s-maxage=86400 and ignore the max-age. stale-while-revalidate=60 (RFC 5861) says: for 60 seconds after it goes stale, serve the stale copy immediately and refresh it in the background. The user never waits for the revalidation. Pair this with a purge on deploy.

6. Know the remaining directives before you need them. must-revalidate forbids serving the stale copy once it expires, even if the origin is unreachable — correct for anything where stale data is worse than an error, wrong for most static content. private restricts storage to the browser. public additionally permits shared storage of responses that would normally be excluded, such as those sent with an Authorization header — which is exactly why you should not sprinkle it on authenticated routes by reflex.

7. Do the same in Apache. Apache splits this across mod_headers and mod_expires:

<IfModule mod_headers.c>
  # Content-hashed build output.
  <FilesMatch "\.[0-9a-f]{8,}\.(js|css|woff2|png|svg)$">
    Header set Cache-Control "public, max-age=31536000, immutable"
  </FilesMatch>

  # The entry document: stored, but revalidated on every load.
  <FilesMatch "^index\.html$">
    Header set Cache-Control "no-cache"
  </FilesMatch>
</IfModule>

<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType image/svg+xml "access plus 1 hour"
  ExpiresByType text/css "access plus 1 hour"
</IfModule>

# Drop the inode so load-balanced nodes agree on the ETag.
FileETag MTime Size

Two Apache-specific notes. Header set applies to successful responses only by default; use Header always set if you need it on error responses too. And do not point both mod_expires and a Header set Cache-Control at the same file — you get one of them, and not reliably the one you meant. Pick one mechanism per path and verify.

8. Prove a conditional request returns 304. Take the ETag from step 1 and send it back in If-None-Match:

curl -I --http1.1 https://example.com/assets/app.a3f9c2e1.js \
  -H 'If-None-Match: "6a54b080-242f5"'
HTTP/1.1 304 Not Modified
Server: nginx/1.24.0
Date: Wed, 15 Jul 2026 14:03:52 GMT
Last-Modified: Mon, 13 Jul 2026 09:31:44 GMT
Connection: keep-alive
ETag: "6a54b080-242f5"
Cache-Control: public, max-age=31536000, immutable

No Content-Length, no body — that is the saving. Note the quotes are part of the ETag value and must be sent back exactly, including a W/ prefix if there was one.

9. Check the timestamp validator too. If-Modified-Since works the same way with the Last-Modified value:

curl -I --http1.1 https://example.com/static/logo.svg \
  -H 'If-Modified-Since: Mon, 13 Jul 2026 09:31:44 GMT'
HTTP/1.1 304 Not Modified
Server: nginx/1.24.0
Date: Wed, 15 Jul 2026 14:04:20 GMT
Last-Modified: Mon, 13 Jul 2026 09:31:44 GMT
ETag: "6a54b080-1f4"
Cache-Control: public, max-age=3600, s-maxage=86400

A policy table by asset type: content-hashed files get public max-age 31536000 immutable, index.html gets no-cache, unhashed static files get a short max-age with a longer s-maxage, and personalized API responses get private no-store

Validate it works

Reduce the check to an exit-code-friendly one-liner. Fetch the real ETag, then send it straight back and print only the status:

ETAG=$(curl -sI --http1.1 https://example.com/assets/app.a3f9c2e1.js \
  | awk -F': ' 'tolower($1)=="etag" {print $2}' | tr -d '\r')
curl -so /dev/null -w '%{http_code}\n' --http1.1 \
  -H "If-None-Match: $ETAG" https://example.com/assets/app.a3f9c2e1.js
304

A 200 here means revalidation is broken and every stale check is re-downloading the whole file. In devtools, the same thing shows up in the Network tab’s Size column: a working policy reads (disk cache) for hashed assets on a repeat navigation, and 304 for HTML.

Now check what the edge actually returns, which is often not what your origin sent:

curl -sI --http1.1 https://example.com/assets/app.a3f9c2e1.js \
  | grep -iE 'cache-control|cf-cache-status|age|vary'
Cache-Control: public, max-age=31536000, immutable
CF-Cache-Status: HIT
Age: 41208
Vary: Accept-Encoding

Age proves a shared cache is holding it and how long it has been there. To compare against the origin directly, bypass DNS with --resolve and point at the origin IP:

curl -sI --http1.1 --resolve example.com:443:203.0.113.10 \
  https://example.com/assets/app.a3f9c2e1.js | grep -i cache-control
Cache-Control: public, max-age=31536000, immutable

If those two disagree, the CDN is rewriting your policy and that is where to go fix it.

Troubleshooting

  • immutable on assets whose filenames never change. This is the one that burns users for a year. public, max-age=31536000, immutable on a plain /js/app.js means a browser that fetched it will not ask again — no reload, no revalidation, nothing short of a manual cache clear. The directive is a promise about the URL, not the file. Only apply it to paths where a content hash is in the name; if your build cannot emit hashes, use a short max-age instead.
  • HTML cached long, so a deploy never lands. Symptom: you ship, the CDN shows the new build, and a subset of users stay on the old one for hours. A max-age on the document froze the references to the old asset names. Set no-cache on HTML, and remember that some CDNs apply a default TTL to HTML even when your origin says otherwise — check Age on the document itself.
  • ETags differ across load-balanced nodes, so nothing ever gets a 304. Two nodes generate different ETags for the same file and each answers 200 to the other’s If-None-Match. On Apache 2.4 the default FileETag MTime Size is already safe; older configs carrying INode forward are not, since inode numbers differ per machine. nginx derives its ETag from mtime and size, so the fix there is making sure your deploy gives every node identical mtimes — rsync -t or a build artifact rather than a per-node checkout. Confirm by curling each node directly and diffing the ETag.
  • Vary fragmenting the cache into uselessness. Each distinct value of a Vary-listed header creates a separate cache entry. Vary: Accept-Encoding is necessary and cheap. Vary: User-Agent shatters one entry into thousands and effectively disables shared caching. Vary: * disables it entirely. Related: nginx weakens a strong ETag to W/"..." when the gzip module compresses on the fly, which is correct behaviour — see gzip and Brotli compression in nginx for how that interacts with pre-compressed files.
  • Set-Cookie quietly disabling shared caching. Many CDNs and reverse proxies refuse to store a response carrying Set-Cookie, since doing so risks handing one user’s session to another. A session middleware that sets a cookie on every response — including static ones — will make your edge hit rate collapse with no error anywhere. Check with curl -I on a static asset: if Set-Cookie is there, that is the bug.
  • Two Cache-Control lines in the response. nginx’s expires directive emits its own Cache-Control: max-age=..., so combining it with add_header Cache-Control gives you both. It is legal HTTP and they get merged, but it is confusing and easy to get wrong — use one or the other. While you are in there: add_header at a location level discards every add_header inherited from the server level, which is how security headers silently vanish on exactly the paths you tuned.

When this is the wrong approach

Caching trades freshness for speed, and some responses have nothing to trade. Anything personalized — an account page, a cart, an authenticated API response — must be private at minimum and usually no-store, because the cost of getting it wrong is showing one user another user’s data. That is not a performance bug; it is a disclosure. Real-time data has the same problem from the other side: if the value is meaningful for less time than a sensible max-age, caching only lets you serve wrong answers faster. Reach for revalidation, a WebSocket, or server-sent events instead.

There is also a scope limit worth naming. These headers govern reuse of a response. They will not make a slow origin fast for the first visitor, or for anything genuinely uncacheable. If your first byte is slow, caching hides it from repeat visitors and from nobody else — measure it first with breaking down request latency with curl and fix the origin. The normative rules live in RFC 9111, and MDN’s HTTP caching guide is the readable version.

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.