HTTP, TLS & Web Performance

Browser Caching and Cache-Control Headers

Understand what each Cache-Control directive does and apply safe caching recipes for pages, static files, APIs and private data.

Key takeaways

  • A fresh cached response is reused without contacting the server, while a stale one usually has to be revalidated first.
  • no-cache allows storage but requires revalidation, and no-store forbids storage altogether.
  • Files whose names change with their contents can safely be cached for a year and marked immutable.
  • Personalized responses need private or no-store so shared caches don't serve them to other people.
  • A response a browser has already stored with a long lifetime can't be recalled from your side.

Cache-Control is the HTTP header that tells browsers and intermediate caches whether they may store a response, for how long they may reuse it without asking, and what to do when that time runs out. For most sites, two rules cover the bulk of it: cache files with a version in their name for a year, and have HTML checked with the server before each reuse.

Get this right and repeat visits become dramatically lighter. Get it wrong and visitors see stale pages, or worse, a shared cache hands one person's data to another.

Fresh, stale and revalidation

The rules for HTTP caching are defined in RFC 9111. The central idea is freshness. A stored response is fresh for a certain lifetime. While fresh, the cache can answer from its copy without any network request.

Once it goes stale, the cache normally asks the server whether the copy is still good. If the response carried a validator, such as an ETag or Last-Modified date, the server can reply 304 Not Modified with no body, and the cache keeps using what it has. That exchange is covered in ETags and conditional requests.

What a cache does with a request
Is there no stored copy that matches? YES Fetch from the server and store it if allowed. 1 NO Is the stored copy still fresh? YES Serve it with no network request. 2 NO Does the copy have a validator? YES Ask the server. A 304 reply renews the copy. 3 NO Fetch again Download a complete new response. Is there no stored copy that matches? 1 IF YES Fetch from the server and store it if allowed. NO Is the stored copy still fresh? 2 IF YES Serve it with no network request. NO Does the copy have a validator? 3 IF YES Ask the server. A 304 reply renews the copy. NO Fetch again Download a complete new response.

Two kinds of cache matter. A private cache belongs to one user, typically the browser's. A shared cache serves many users, such as a content delivery network or a company proxy.

The directives that matter

Directive Meaning
max-age=N Fresh for N seconds
s-maxage=N Lifetime for shared caches, overriding max-age there
no-cache May store, but must revalidate before each reuse
no-store Don't store this response
private Only a private cache may store it
public Shared caches may store it, even in some cases where they otherwise wouldn't
must-revalidate Once stale, don't reuse without checking
immutable The content won't change while fresh, so don't revalidate on reload
stale-while-revalidate=N May serve a stale copy for N seconds while refreshing in the background
stale-if-error=N May serve a stale copy if fetching a new one fails

immutable comes from RFC 8246, and the two stale- extensions from RFC 5861. Support for extensions varies between browsers and delivery networks, and unknown directives are ignored.

The names cause real confusion. no-cache sounds like "never cache", but it means "never reuse without asking". If you truly don't want a copy written down, use no-store.

How to pick a lifetime

Start from the consequence of being wrong. Ask what happens if a visitor sees yesterday's copy of this resource. For a decorative background, nothing. For a stylesheet that must match new HTML, a broken layout. For an account balance, a serious complaint.

Then ask whether you can change the address. If you can, the question disappears: give the file a very long lifetime and publish new versions under new names. If you can't, because the URL is bookmarked or defined by convention, the lifetime is your maximum delay for corrections. Pick the longest delay you'd be comfortable explaining.

Also consider how often the resource is requested again. A long lifetime on something each visitor views only once helps little in their browser, though it may help a great deal in a shared cache that serves thousands of people. That's the case where s-maxage with a modest browser lifetime fits well.

APIs follow the same logic. A list of countries can be cached for a day. Search results for a signed-in user shouldn't be shared. A frequently polled status endpoint may benefit from even a few seconds of shared freshness, since many requests collapse into one.

Recipes that work

Versioned static files. Build tools can put a hash of the content in the filename, as in app.3f9a1c.js. A changed file gets a new name, so the old one never needs to expire early.

Cache-Control: public, max-age=31536000, immutable

HTML pages. The HTML refers to your versioned files, so it should be checked each time:

Cache-Control: no-cache
ETag: "a1b2c3"

Public pages that can be slightly old. Let browsers recheck while a shared cache holds the page briefly:

Cache-Control: public, max-age=0, s-maxage=300, stale-while-revalidate=60

Personalized pages. Account pages, baskets and anything behind a sign-in:

Cache-Control: private, no-cache

Highly sensitive responses, such as bank statements or one-time secrets:

Cache-Control: no-store

Unversioned assets such as logo.png or favicon.ico deserve a moderate lifetime, perhaps hours or days, depending on how quickly you need a replacement to appear.

Choosing a policy by content
Hashed assets Same name always means same bytes. Cache for a year. HTML documents Store, but revalidate before reuse. Signed-in views Private cache only, or no storage. Unversioned files Moderate lifetime you can live with. Hashed assets Same name always means same bytes. Cache for a year. HTML documents Store, but revalidate before reuse. Signed-in views Private cache only, or no storage. Unversioned files Moderate lifetime you can live with.

Setting the headers

In nginx:

location /assets/ {
    add_header Cache-Control "public, max-age=31536000, immutable";
}

location / {
    add_header Cache-Control "no-cache";
}

Note that add_header directives in an inner block replace inherited ones instead of adding to them, which can silently drop security headers.

In Apache, with mod_headers enabled:

<FilesMatch "\.[0-9a-f]{6,}\.(js|css)$">
    Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>

Application frameworks and hosting platforms usually offer their own settings. Check the final headers as the browser receives them, since a proxy or network in between may rewrite them.

Cookies, authorization and shared caches

Shared caches follow a protective rule for requests that carry an Authorization header: they don't reuse the response for other users unless the server explicitly allows it, for example with public, s-maxage or must-revalidate. Cookies get no such automatic protection in the HTTP rules. Many delivery networks refuse to cache responses that set cookies, but that's product behavior you should verify instead of assuming.

So label personal responses yourself. A framework that adds public to everything, or a rewrite rule that treats any address ending in .css as static, can turn a private page into a shared one. Attackers have deliberately requested made-up file-like paths under account pages to trigger exactly this, a problem known as web cache deception. The defense is to cache according to what the application actually returned, send private or no-store on anything personal, and return 404 for paths that don't exist.

After signing out, sensitive pages shouldn't linger on a shared computer. no-store on those responses is the appropriate tool. The related cookie settings are explained in how cookies work in HTTP.

Older headers and hidden behavior

Expires gives an absolute date and time. When max-age is present, it takes precedence. Pragma: no-cache is a leftover from HTTP/1.0 that you rarely need.

Age, added by shared caches, says how many seconds the response has already spent in cache. A browser subtracts it from the remaining lifetime.

If a response has no explicit lifetime, a cache may apply heuristic freshness, often a fraction of the time since Last-Modified. This surprises people who believed that sending no header meant no caching. Always state your intent.

Vary lists request headers that change the response. Vary: Accept-Encoding is common and sensible. Vary: User-Agent splinters a cache into countless variants, and Vary: * effectively prevents reuse.

You can explore how lifetimes and Age combine with an HTTP cache age and freshness simulator.

Checking what happens

Fetch just the headers:

curl -I https://example.com/assets/app.3f9a1c.js

In browser developer tools, the Network panel shows when a request was served from memory or disk cache, and when the server answered 304. Make sure the "disable cache" checkbox is off while testing. A normal navigation, a reload and a forced reload behave differently, so test the way visitors browse: by following links.

The back and forward buttons use a separate in-memory snapshot in modern browsers, sometimes called the back/forward cache. It restores the whole page and isn't governed by freshness in the same way.

Rolling out a new policy

Change caching in small steps. Begin with short lifetimes, confirm the headers arrive as intended, then lengthen them for the files that are safely versioned. Keep a note of what each path should send, and add an automated check that requests a few representative addresses after each deployment and compares the headers. Configuration drift is common, and nobody notices a missing header until the site feels slow or stale.

What can go wrong

  • Long lifetimes on unversioned files. Visitors keep an old stylesheet with new HTML, and the layout breaks.
  • Private data marked public. A shared cache serves one account's page to another. Audit anything that depends on cookies or authorization.
  • Cookies on cacheable responses. A stored Set-Cookie header is dangerous in shared caches. Don't set cookies on static assets.
  • Deleting old assets too soon. An open tab may still request the previous version.
  • Blanket no-store. It's safe but throws away nearly every speed benefit.

If you've already shipped a mistake, the remedies are in making updates appear.

Common questions

Does clearing my own browser cache fix it for everyone?

No. It only removes your copy. Other visitors keep theirs until it expires or you change the URL that the page refers to.

Should HTTPS pages still use caching?

Yes. Browsers cache HTTPS responses according to these same headers. A CDN that terminates TLS for you can cache them too, which is why private and no-store matter. For the wider set of headers to review, see HTTP headers every site owner should know.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in HTTP, TLS & Web Performance →

Latest news on this topic