Cache-Control headers decide whether a browser or CDN reuses a response or asks your server again, which makes them one of the cheapest ways to speed up repeat visits and reduce server load. They are also a common cause of real incidents: a stylesheet that stays stale after a deploy, a logged-in page served to the wrong visitor from a CDN, or an origin that never caches anything at all. This guide explains each directive in plain terms, gives a policy for HTML, assets and APIs, shows the Nginx configuration with its biggest gotcha, covers WordPress and Cloudflare specifics, and ends with curl tests and a small Python script that audits a list of URLs.

Cache-Control headers policy: versioned static assets cached for a year as immutable, HTML revalidated with no-cache, private responses for logged-in users and no-store for sensitive data
Cache-Control headers by resource type: versioned assets cached for a year, HTML revalidated, private and sensitive responses kept out of shared caches.

From my own work: On WordPress servers I take over, I usually find one of two extremes: no caching headers on anything, or a plugin that sets a long public max-age on HTML. The second is worse, because a cart page or a stale price can be cached in a CDN. A clear policy per resource type, set in Nginx, removes both problems.

How HTTP caching decides: fresh, stale and revalidated

Under RFC 9111, a stored response is fresh until its age passes the freshness lifetime, usually given by max-age. A fresh response is reused without contacting the server. Once it is stale, the cache revalidates: it sends a conditional request with If-None-Match (the stored ETag) or If-Modified-Since (the stored Last-Modified), and the server answers 304 Not Modified with no body if nothing changed (RFC 9111). Private caches belong to one user, like the browser; shared caches serve many users, like a CDN or a reverse proxy.

Cache-Control directives reference

Directive Meaning Typical use
max-age=N Fresh for N seconds in any cache Static assets, public API data
s-maxage=N Overrides max-age in shared caches only; browsers ignore it Let the CDN keep HTML longer than browsers
no-cache May be stored, but must be revalidated before every reuse HTML that must always be current
no-store Must not be stored anywhere Account pages, payment steps, tokens
private Only the user’s own browser may store it Personalised pages
public Shared caches may store it, even with authentication Assets; rarely needed otherwise
must-revalidate Once stale, never serve without revalidating Data where stale is worse than an error
immutable Do not revalidate while fresh, even on reload Fingerprinted or versioned asset URLs
stale-while-revalidate=N Serve stale for up to N seconds while refreshing in the background HTML or API responses at a CDN
stale-if-error=N Serve stale for up to N seconds if the origin fails Resilience during origin outages

The MDN reference has the full list with browser support details (MDN: Cache-Control); the two stale directives come from RFC 5861 (RFC 5861). The one people misread most is no-cache: it does not mean do not cache. It means always check first, which is often exactly what you want for HTML, because a 304 response is tiny.

A caching policy by resource type

  • Versioned static assets (app.3f9a1c2b.js, or WordPress files with ?ver=): public, max-age=31536000, immutable. A new release changes the URL, so the old copy is never wrong.
  • Unversioned images and fonts: a long but finite lifetime, such as 30 days, so a replaced file eventually updates.
  • Public HTML: no-cache for browsers, with ETag or Last-Modified so revalidation is cheap. If a CDN caches HTML, give it a separate lifetime (see the CDN section).
  • Personalised HTML, carts, checkout, account pages: private, no-store. Never let them reach a shared cache.
  • APIs: no-store for user data; short max-age with stale-while-revalidate for public, slowly changing data.

Nginx configuration and the add_header trap

In Nginx, add_header sets response headers and expires writes both Expires and Cache-Control: max-age (Nginx: headers module). Add always so the header is also sent on error responses where that matters. The trap: add_header directives are inherited from the enclosing level only if the current level defines none. A single add_header in a location silently removes every security header you set at the server level for that location.

# /etc/nginx/snippets/security-headers.conf
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
server {
    listen 443 ssl;
    http2 on;
    server_name example.com;
    root /var/www/example.com;

    include snippets/security-headers.conf;

    # Fingerprinted or ?ver= versioned assets
    location ~* .(?:css|js|mjs|woff2)$ {
        include snippets/security-headers.conf;     # repeat: add_header is not inherited here
        add_header Cache-Control "public, max-age=31536000, immutable" always;
        access_log off;
        try_files $uri =404;
    }

    # Images: long, but not forever
    location ~* .(?:png|jpe?g|gif|webp|avif|svg|ico)$ {
        include snippets/security-headers.conf;
        add_header Cache-Control "public, max-age=2592000" always;
        access_log off;
        try_files $uri =404;
    }

    # WordPress front end
    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ .php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.4-fpm.sock;
        # WordPress sends no-cache headers itself for admin and logged-in requests
    }
}

Nginx sends ETag and Last-Modified for static files by default, so revalidation works without extra configuration. For PHP pages, let WordPress or your page cache decide; WordPress already sends no-cache style headers on admin, login and logged-in requests.

If you run a server-side page cache, the browser headers above combine with the techniques in Nginx FastCGI cache for WordPress. Long-lived image caching pays off most once images are already small, as in converting WordPress images to WebP and AVIF.

CDNs and Cloudflare: s-maxage, CDN-Cache-Control and stale content

A CDN is a shared cache, so it reads s-maxage and public/private. Two details matter on Cloudflare. First, by default it caches static file extensions but not HTML; caching HTML needs a cache rule, which is covered in Cloudflare cache rules for WordPress. Second, under RFC 9111 s-maxage implies proxy-revalidate, and Cloudflare documents that s-maxage therefore disables stale-while-revalidate (Cloudflare: Cache-Control). If you want background refresh at the edge, use max-age with stale-while-revalidate, or set a CDN-specific header.

RFC 9213 defines targeted headers that only CDNs read. CDN-Cache-Control applies to any CDN that supports it, and Cloudflare-CDN-Cache-Control only to Cloudflare. They let you give the edge and the browser different rules without tricks:

# Browser always revalidates; the CDN keeps HTML for 5 minutes
# and refreshes it in the background for up to 1 minute after that
Cache-Control: no-cache
CDN-Cache-Control: max-age=300, stale-while-revalidate=60

Purge the CDN on publish or deploy, and make sure responses that set cookies, or pages for logged-in users, bypass the edge cache entirely.

Cache headers, Core Web Vitals and crawling

Good asset caching makes repeat page views faster, which helps real-user metrics such as LCP for returning visitors; the full picture of what moves those metrics is in the Core Web Vitals guide. For crawling, Google has said its crawlers support HTTP caching with ETag and Last-Modified: if the content has not changed, returning 304 without a body saves resources on both sides (Google Search Central: HTTP caching). Make sure the ETag changes whenever the content does, and that a 304 is never returned for changed content.

Test cache headers with curl

# headers only
curl -sI https://example.com/ | grep -iE 'cache-control|etag|last-modified|age|cf-cache-status'

# asset headers
curl -sI 'https://example.com/wp-includes/css/dist/block-library/style.min.css?ver=6.9'

# conditional request: should return 304 with no body
ETAG=$(curl -sI https://example.com/style.css | awk -F': ' 'tolower($1)=="etag"{print $2}' | tr -d 'r')
curl -sI -H "If-None-Match: $ETAG" https://example.com/style.css | head -1

# CDN hit or miss: run twice and compare cf-cache-status / age
curl -sI https://example.com/ | grep -iE 'cf-cache-status|age'

A Python script to audit Cache-Control headers

For more than a handful of URLs, a script is faster than reading headers by hand. This one uses only the standard library, flags short lifetimes on static files, missing immutable on versioned URLs, long public caching of HTML, cookies on shareable responses, and missing validators:

"""Audit Cache-Control headers for a list of URLs (standard library only).

Usage: python cache_audit.py https://example.com/ "https://example.com/app.css?ver=1.2"
"""
from __future__ import annotations

import re
import sys
import urllib.request

STATIC = re.compile(r".(css|js|mjs|woff2?|png|jpe?g|gif|webp|avif|svg|ico)(?|$)", re.I)
HASHED = re.compile(r"[.-][0-9a-f]{8,}.|[?&]ver=", re.I)


def directives(value: str) -> dict[str, str | None]:
    out = {}
    for part in value.split(","):
        part = part.strip()
        if not part:
            continue
        key, _, val = part.partition("=")
        out[key.lower()] = val.strip('"') or None
    return out


def check(url: str) -> list[str]:
    req = urllib.request.Request(url, method="GET", headers={"User-Agent": "cache-audit/1.0"})
    with urllib.request.urlopen(req, timeout=20) as resp:
        h = resp.headers
    cc = directives(h.get("Cache-Control", ""))
    max_age = int(cc.get("max-age") or 0)
    notes = [f"Cache-Control: {h.get('Cache-Control', '(none)')}"]
    for name in ("ETag", "Last-Modified", "Age", "CF-Cache-Status", "X-Cache", "Vary"):
        if h.get(name):
            notes.append(f"{name}: {h[name]}")
    if STATIC.search(url):
        if "no-store" in cc or max_age < 86400:
            notes.append("WARN static asset cached for less than a day")
        if HASHED.search(url) and "immutable" not in cc:
            notes.append("TIP versioned URL: add 'immutable' and max-age=31536000")
    else:
        if "public" in cc and max_age > 600 and "s-maxage" not in cc:
            notes.append("WARN HTML cached in browsers for over 10 minutes; prefer a short max-age or no-cache")
        if "set-cookie" in {k.lower() for k in h.keys()} and "private" not in cc and "no-store" not in cc:
            notes.append("WARN response sets a cookie but may be stored by shared caches")
    if not (h.get("ETag") or h.get("Last-Modified")):
        notes.append("TIP no ETag or Last-Modified: revalidation always downloads the full body")
    return notes


if __name__ == "__main__":
    for url in sys.argv[1:]:
        print(url)
        try:
            for line in check(url):
                print("   ", line)
        except Exception as exc:
            print("    ERROR", exc)

Feed it your homepage, a product or post page, a cart or account URL, and two or three asset URLs copied from the page source. Run it after every Nginx or CDN change, because one misplaced add_header can change several of these at once. If server response time itself is the bottleneck, start with diagnosing slow TTFB on a WordPress VPS before tuning caches.

Cache-Control headers checklist

  • Versioned assets: public, max-age=31536000, immutable.
  • Unversioned images and fonts: a long but finite max-age.
  • Public HTML: no-cache with ETag or Last-Modified; CDN lifetime set separately.
  • Logged-in, cart, checkout and account responses: private, no-store, bypassing the CDN.
  • Security headers repeated in every Nginx location that uses add_header.
  • No s-maxage where you rely on stale-while-revalidate at Cloudflare.
  • Conditional requests return 304; the CDN is purged on deploy.

Want this done on your own server or site?

I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.

FAQ

What is the difference between no-cache and no-store?

no-cache allows a response to be stored but requires the cache to check with the server before each reuse, usually with a cheap 304 response. no-store forbids storing the response at all, which is the right choice for sensitive or personalised data.

What Cache-Control header should static files have?

For files whose URL changes when the content changes, such as fingerprinted names or ?ver= query strings, use public, max-age=31536000, immutable. For files whose URL never changes, use a long but finite max-age, such as 30 days.

Should HTML pages be cached?

Browsers should usually revalidate HTML with no-cache so visitors always see current content. A CDN can cache public HTML for a few minutes if you purge it on publish and never cache pages for logged-in users or pages that set cookies.

What does immutable mean in Cache-Control?

It tells the browser that the response will never change while it is fresh, so the browser does not revalidate it even when the user reloads the page. It is only safe for versioned URLs.

Why does Nginx drop my security headers on some files?

add_header directives are inherited from the server block only when the location block defines none of its own. Adding a Cache-Control add_header in a location removes the inherited headers, so include them again in that location.

Sources

NEW BLOGS. REAL STRATEGIES. REAL RESULTS.

Join our community and receive powerful SEO tips, web optimization guides, and growth strategies as soon as they’re published.

Don’t just read blogs — stay ahead of the competition.

We don’t spam! Read our privacy policy for more info.

Share.

Comments are closed.