Cache-Control Headers: Setting CDN and Browser Caching Correctly

max-age, s-maxage, no-cache, no-store, stale-while-revalidate, ETag and Vary: Cache-Control sets by content type, cache leaks and verification with curl.
Technical summary
Technology
HTTP Caching (RFC 9111), Cache-Control, ETag, Vary, CDN, Nginx, Apache, curl
Topic
Configuring HTTP cache headers by content type
Level
Intermediate
Prerequisites
  • Knowledge of HTTP request/response structure
  • Access to the web server or CDN configuration
  • Using curl on the command line
In this article7 sections

Content has been updated but the visitor still sees the old page; or the reverse, there’s a CDN but every request goes to the origin server. The root of both complaints is usually in the same place: the Cache-Control header. Before a response reaches the visitor, it passes through the browser cache, the CDN and, if there is one, a reverse proxy; this header decides how long each layer stores it and when it revalidates. This guide explains HTTP caching semantics based on RFC 9111 and proposes tool-independent header sets for static assets, HTML and session-based pages.

HTTP cache layers

RFC 9111 divides caches into two types. A private cache belongs to a single user; the browser cache is the typical example. A shared cache serves responses to multiple users; CDNs and reverse proxies are in this group. The practical consequence of the distinction is clear: user-specific content (account page, cart) can be stored in the browser but must never be stored in a shared cache. If this line is crossed, one user’s page goes to another.

A response’s lifetime in the cache is managed with two concepts:

  • Freshness: The time during which the response can be used without asking the origin server. It’s set with max-age or s-maxage. The Age header shows how long a response served from the cache has been stored.
  • Validation: When the freshness lifetime expires, the cache asks the origin server “is this still valid?” The server compares with ETag or Last-Modified; if the content hasn’t changed, it returns a bodiless 304 Not Modified.

Table of Cache-Control directives

Commonly used response directives and their meanings are below. stale-while-revalidate and stale-if-error are defined in RFC 5861 and immutable in RFC 8246; the others are in RFC 9111.

Directive Meaning Watch out for
max-age=N Considered fresh for N seconds Applies to all caches
s-maxage=N Freshness for shared caches only Overrides max-age on the CDN
no-cache Can be stored, must be validated on every use Doesn’t mean “no caching”
no-store Not stored in any cache For sensitive data; affects back-button performance
private Only the browser may store it User-specific content
public Shared caches may store it too Allows storage even for authenticated responses
must-revalidate Can’t be served after going stale without validation Returns an error if the origin is unreachable
stale-while-revalidate=N Stale response served for N seconds while refreshed in the background Support varies by browser and CDN
immutable Content doesn’t change during its freshness lifetime Only for versioned file names

The Expires header is an older mechanism and is ignored if max-age is present. Pragma: no-cache exists only for HTTP/1.0 compatibility; it isn’t needed in a modern configuration. Some CDNs support the CDN-Cache-Control header defined in RFC 9213; it sets only the CDN’s behavior without touching the Cache-Control value sent to the browser. The pair most often confused in the field is no-cache and no-store. One says validate, the other says (don’t) store.

Long-term caching for static assets

From a web performance perspective, the most efficient strategy for CSS, JavaScript, font and image files is: when the content changes, the URL changes too, and the file stays in the cache for a very long time. This is called “fingerprinting” or cache busting: a content hash is added to the file name, as in app.3f9a1c.css, or a version parameter is used, as in style.css?ver=2.4.0. When the URL changes, the cache key changes too and the user gets the new file.

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

In Nginx, this header is set by extension like this:

location ~* \.(?:css|js|woff2|avif|webp|jpg|jpeg|png|svg)$ {
    add_header Cache-Control "public, max-age=31536000, immutable" always;
    access_log off;
    try_files $uri =404;
}

In Apache, if mod_headers is enabled:

<FilesMatch "\.(css|js|woff2|avif|webp|jpe?g|png|svg)$">
    Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>

This rule has a precondition: the URL of every file given long-term caching by extension must change when its content changes. In WordPress, theme and plugin files are versioned with the ?ver= parameter; but plugins that replace an image in the media library with the same name, or files uploaded by hand without a version parameter, break this assumption. The result: the old logo for a year. In Nginx, nested location blocks and add_header inheritance rules can give unexpected results; defining a single add_header in a child block cancels all the add_header lines in the parent block. Verify the configuration with a header check after every change; for header management at the reverse proxy layer, see the Nginx reverse proxy guide.

Strategy for HTML and dynamic content

Since the URL of HTML doesn’t change, it can’t be given long browser caching; if it is, content updates don’t reach users for days. The balanced approach is to validate every time in the browser and define a short freshness lifetime on the CDN:

# Public HTML for visitors without a session
Cache-Control: public, max-age=0, s-maxage=600, stale-while-revalidate=60

# User-specific pages (account, cart, checkout)
Cache-Control: private, no-cache

# Responses containing sensitive data
Cache-Control: no-store

In the first line, the browser validates the page on every visit; the CDN serves it for 10 minutes without going to the origin server, and for requests arriving in the 60 seconds after that, it serves the stale copy while refreshing in the background. So as not to wait 10 minutes when content is published, connect a purge of the related URLs to the publishing workflow: the updated post, the home page, the category archive and the sitemap, if any. Some CDNs offer tag-based purging; this feature varies by plan and provider. Without purging, shortening the TTL isn’t a solution. It only lowers the hit rate.

Redirects are often overlooked. 301 responses can be cached by default even without an explicit cache header, and browsers can keep them for a long time. Fixing a wrong 301 on the server doesn’t fix browsers that already received it. During a migration or restructuring, use 302 first for redirects you’re not sure are permanent, or give them an explicit max-age.

Vary, cookies and cache leaks

The Vary header tells the cache which request headers to keep separate copies by for the same URL. Vary: Accept-Encoding is standard for separating compressed and uncompressed copies. Vary: User-Agent or Vary: Cookie, however, make almost every request unique and crash the hit rate in a shared cache. CDN support for Vary is also limited; most handle only certain values.

The real risk is a user-specific response being written to a shared cache and served to other users. This “cache leak” isn’t a performance problem but a data leak. Typical causes:

  • public or s-maxage in HTML returned to a signed-in user.
  • A CDN rule ignoring the cookie and storing the response even though the response has a Set-Cookie.
  • Session cookies listed incompletely in the cache bypass rule. Cookies prefixed wordpress_logged_in_, wp-postpass_ and comment_author_ for WordPress, and woocommerce_items_in_cart and wp_woocommerce_session_ for WooCommerce, are typical examples.
  • Personalized fragments (cart counter, user name) being output into the HTML on the server side.

The lasting solution for the last item is to separate personal fragments from the HTML and fill them with a separate, uncached request. For typical scenarios on e-commerce sites, see the WooCommerce cache errors guide; for how page cache, CDN and object cache work together, see the Cloudflare, WP Rocket and Redis guide.

Verifying headers and troubleshooting

In corporate web infrastructure, verify the cache configuration on the command line, not in the browser. The browser can give misleading results because of its own cache and extensions. Since some servers return different headers to HEAD than to GET, making a GET request and discarding the body is more reliable:

# Show response headers, discard the body
curl -s -o /dev/null -D - https://www.example.com/

# Request like a browser that accepts compression
curl -s -o /dev/null -D - -H 'Accept-Encoding: br, gzip' https://www.example.com/assets/app.css

# Conditional validation: a 304 is expected with the ETag from the previous response
curl -s -o /dev/null -D - -H 'If-None-Match: "5f2a-63b1c9e0"' https://www.example.com/

# Request with a session cookie: should not come from the cache
curl -s -o /dev/null -D - -H 'Cookie: wordpress_logged_in_test=1' https://www.example.com/

Headers to check in the output and how to read them:

Item What it shows
Cache-Control The policy applied by the origin or the CDN
Age How many seconds the response has been in the shared cache
ETag / Last-Modified Whether validation is possible
Vary Request headers that are part of the cache key
Provider-specific status header Hit status; e.g. cf-cache-status in Cloudflare (HIT, MISS, EXPIRED, BYPASS, DYNAMIC)

The order of checks is simple. Send the same request twice in a row: if the second response shows no hit and Age doesn’t increase, the CDN isn’t storing the response; look first at the header the origin server sends, then at the CDN rule. Then repeat the same request with a session cookie. If a request with a session cookie shows a hit, there’s a serious risk of a cache leak. Fix that first.

To design page cache, CDN rules and header policies together on corporate WordPress sites, see our WordPress cache and CDN optimization service. The normative definition of all directives is in RFC 9111.

Frequently asked questions

Does no-cache mean “not cached”?

No. no-cache says the response can be cached but must be validated with the origin server before every use. Validation is done with ETag or Last-Modified; if the content hasn’t changed, the server returns a bodiless 304 response. If you want the response not to be stored in any cache, use no-store.

What happens if no Cache-Control header is sent?

According to RFC 9111, if there’s no explicit freshness information, caches can calculate heuristic freshness for certain status codes; if there’s a Last-Modified header, a duration is set based on the file’s age. In other words, the same file is stored for unpredictable durations in different browsers and CDNs. Define an explicit Cache-Control value for every response type; that’s the only way to remove the uncertainty.

What does the immutable directive do?

immutable indicates that the response won’t change during its freshness lifetime. Supporting browsers don’t send conditional validation requests for these resources even when the user reloads the page. Use it only on assets that carry a version or hash in the file name; if it’s given to a file whose content changes at the same URL, users keep seeing the old version.

Is it safe to cache HTML on a CDN?

It’s safe for pages where the same content is shown to visitors who aren’t signed in, and TTFB usually improves noticeably on a cache hit. The conditions are: requests carrying session, cart and personalization cookies must bypass the cache, responses containing Set-Cookie must not be written to the shared cache, and the related URLs must be purged when content is updated.

Support

Contact us for support or a discovery session on this topic.

Contact form
[email protected]

Eretek Web

We build and maintain corporate websites, WordPress and CMS platforms, intranet and SharePoint portals, document management, and form and approval workflows, and keep them secure and up to date.

Knowledge Center

Other articles