You are currently viewing CDN Setup Without Breaking Dynamic Content

CDN Setup Without Breaking Dynamic Content

Somebody puts a CDN in front of the site on a Friday. The homepage gets faster, the bill goes down, everyone is pleased. On Monday a customer emails to say they logged in and saw someone else’s name in the header.

That is the failure mode worth taking seriously. Not slowness, not downtime — the CDN cached a page that was personalised for one user and served it to everybody else. And you will not notice, because your browser holds a session and looks fine. The people seeing the broken version are the ones who never contact you.

Getting CDN setup right for a dynamic site is not about finding the right toggle in a dashboard. It is about deciding, per route, what is public and what is personal, and then making the origin say so clearly enough that no edge node has to guess.

Sort your routes before touching any config

Every URL on your site falls into one of three buckets. Write the list out — actually write it, this takes ten minutes and prevents the incident above.

  • Static assets. CSS, JS, images, fonts. Identical for everyone, content-addressed if your build is sensible. Cache these hard, for a year.
  • Public dynamic. Generated by the application but identical for every anonymous visitor. Blog posts, product pages, category listings. This is where the real performance win lives, and where most people leave everything uncached out of nervousness.
  • Private dynamic. Anything personalised or authenticated. Carts, dashboards, checkout, admin, most API responses. Never cached at a shared cache, no exceptions.

The middle bucket is the whole game. If you cache only the first bucket you have built an asset CDN and left the expensive work untouched. If you accidentally cache the third, you have a data leak.


The header that separates the buckets

The single most useful thing to understand is the difference between private and no-store, because people use them interchangeably and they mean very different things.

# Static assets with a content hash in the filename
Cache-Control: public, max-age=31536000, immutable

# Public dynamic: edge caches it, browser revalidates
Cache-Control: public, s-maxage=300, max-age=0, must-revalidate

# Personalised: browser may cache, shared caches must not
Cache-Control: private, no-store

# Genuinely sensitive: nobody stores this anywhere
Cache-Control: no-store

private means “a browser cache may keep this, a shared cache may not”. no-store means “do not write this to disk anywhere”. For an authenticated dashboard you want both. For a bank statement you want no-store alone.

The other key pair is s-maxage versus max-age. s-maxage applies only to shared caches — the CDN — and overrides max-age there. That lets you cache a product page at the edge for five minutes while telling browsers to revalidate every time, so a price change propagates in five minutes rather than living in someone’s browser for an hour.

Set caching headers at the origin, per route, and let the CDN follow them. Configuring cache rules only in the CDN dashboard means the policy lives somewhere your application code cannot see and your staging environment does not have.

Vary, and how it quietly ruins your hit rate

Vary tells caches that the response depends on a request header, so a separate copy is stored per distinct value. Used precisely it is essential. Used carelessly it destroys your cache.

# Fine. A handful of encodings, a handful of variants.
Vary: Accept-Encoding

# Also fine if you genuinely serve different content per language
Vary: Accept-Encoding, Accept-Language

Now the one to avoid:

# Effectively disables caching. Every browser build is a distinct
# User-Agent string, so every visitor gets their own cache entry.
Vary: User-Agent

If you need device-specific responses, most CDNs expose a normalised device-type value with two or three possible values. Use that rather than the raw header.

Vary: Cookie deserves its own warning. It looks like a safe way to separate logged-in from anonymous traffic, and it is not — every visitor carries slightly different cookies from analytics and consent tools, so you get a near-unique cache key per person. The correct approach is to make the presence of a session cookie bypass the cache entirely, rather than varying on it.


Cookies are where sites actually break

Two rules, and between them they prevent most CDN incidents.

Rule one: a session cookie means bypass

If a request arrives carrying your session cookie, it should go to origin uncached. Most CDNs let you express this as a cache rule; in nginx, if you are running your own edge, it is a variable:

map $http_cookie $bypass_cache {
    default                 0;
    "~*wordpress_logged_in" 1;
    "~*woocommerce_items"   1;
    "~*comment_author"      1;
    "~*PHPSESSID"           1;
}

location / {
    proxy_cache            edge_cache;
    proxy_cache_bypass     $bypass_cache;   # do not serve from cache
    proxy_no_cache         $bypass_cache;   # do not write to cache
    proxy_cache_valid      200 301 302 5m;
    proxy_cache_use_stale  error timeout updating http_500 http_502 http_503 http_504;
    proxy_cache_lock       on;

    add_header X-Cache-Status $upstream_cache_status always;
    proxy_pass http://origin;
}

You need both directives. proxy_cache_bypass stops a logged-in user being served a cached anonymous page. proxy_no_cache stops their personalised response being written into the cache for everyone else. Setting only the first is a common and dangerous mistake — the read path is protected while the write path is wide open.

That X-Cache-Status header is not decoration. It is how you verify any of this actually works.

Rule two: strip cookies you do not need

Analytics and consent tools set cookies on every visitor. If your CDN treats any cookie as a bypass signal, your anonymous traffic stops being cacheable the moment you add a tag manager. Configure the CDN to ignore everything except the specific cookies that matter, and be explicit about which those are.

Query strings, and the cache-key explosion

By default many CDNs include the full query string in the cache key. Then a marketing campaign starts appending utm_source, utm_medium, fbclid and friends, and one page becomes thousands of cache entries that each miss exactly once.

Decide deliberately which parameters affect the response:

  • Include parameters that change the content — ?page=2, ?sort=price, ?category=boots.
  • Ignore tracking parameters entirely. They never change what the server renders.
  • Normalise order where the CDN supports it, so ?a=1&b=2 and ?b=2&a=1 are one entry rather than two.

An allowlist is safer than a blocklist here. New tracking parameters appear constantly; the set of parameters your application actually reads changes rarely.


Keeping dynamic pages cached without going stale

The usual objection to caching public dynamic pages is that content changes. Two mechanisms solve this, and together they let you cache aggressively without serving stale content for long.

Stale-while-revalidate

Cache-Control: public, s-maxage=60, stale-while-revalidate=600, stale-if-error=86400

Read that as three separate promises. Fresh for sixty seconds. For the following ten minutes, serve the stale copy immediately while fetching a fresh one in the background — so nobody waits. And if the origin is throwing errors, keep serving the stale copy for a day rather than showing a 502.

That last directive turns your CDN into a partial outage shield. It is one of the highest-value headers on this page and it costs nothing.

Purge on change

Time-based expiry is a blunt instrument. If your application knows when a product price changed, tell the CDN immediately rather than waiting for a TTL.

Tag-based purging is the version worth building toward — tag responses by the entities they contain, then purge by tag when an entity changes:

# Origin response for a product page
Cache-Tag: product-1234, category-boots, layout-main

Update product 1234 and you purge one tag, invalidating the product page, every category listing it appears on, and the homepage if it is featured — without knowing any of those URLs in advance. Header name and support vary by provider, so check what yours calls it.

Verifying it before you point DNS

Test with curl, not a browser. Your browser has cookies, a warm local cache and an opinion; curl tells you the truth.

# What headers is the origin actually sending?
curl -sI https://example.com/products/boots | grep -i 'cache-control|vary|set-cookie'

# Twice in a row: second request should show a HIT
curl -sI https://example.com/products/boots | grep -i 'x-cache|age'
curl -sI https://example.com/products/boots | grep -i 'x-cache|age'

Now the test that matters most. Request an authenticated page with a real session cookie and confirm it never returns a cache hit:

curl -sI https://example.com/account 
  -H "Cookie: session=<a-real-session-value>" 
  | grep -i 'x-cache|cache-control'

You want BYPASS or MISS, and Cache-Control: private. If that ever shows HIT, stop and fix it before going further.

The leak test, which is the one people skip: fetch a personalised page with a session, then fetch the same URL with no cookies at all and confirm you get the anonymous version.

# With a session
curl -s https://example.com/account -H "Cookie: session=<value>" | grep -i 'welcome back'

# Immediately after, with nothing. Should NOT show the personalised content.
curl -s https://example.com/account | grep -i 'welcome back'

If the second command finds personalised content, the CDN cached a private response. That is the Monday-morning email, and you have just caught it before your customers did.

Test the edge before DNS points at it

curl -sI https://example.com/ --resolve example.com:443:<edge-ip>

That sends a real request to a specific edge node with the correct hostname and TLS SNI, without changing DNS. It is how you find out whether the whole thing works before any user does.


Things that break in ways nobody expects

Client IPs all become the CDN’s

Your logs fill with edge node addresses, rate limiting starts throttling everyone at once, and geolocation breaks. The real address arrives in a forwarded header, and your origin has to be configured to trust it — but only from the CDN’s address ranges. Trusting X-Forwarded-For from anywhere lets any visitor claim any IP they like, which turns a logging annoyance into an authentication bypass.

Redirect loops

The CDN talks to your origin over HTTP, the origin sees a non-HTTPS request and redirects to HTTPS, which comes back through the CDN, forever. Either terminate TLS at the origin too, or have the origin trust X-Forwarded-Proto when deciding whether to redirect.

POST responses getting cached

Shouldn’t happen by default, but a badly written cache rule can do it, and the result is one user’s form submission response served to the next person. Only cache GET and HEAD. Ever.

Websockets and streaming

Websocket upgrades and server-sent events need to pass through untouched. Buffering breaks streaming responses silently — the connection works, the data just arrives in one lump at the end, which looks like an application bug rather than a proxy setting.

Set-Cookie on a cacheable response

If a public page returns Set-Cookie and gets cached, every subsequent visitor receives that cookie — potentially somebody’s session identifier. Most CDNs refuse to cache responses carrying Set-Cookie, but not all, and not always. Check your origin is not setting cookies on pages you intend to cache.

Rolling it out without a bad week

  1. Write down the route list. Three buckets, every path accounted for.
  2. Set headers at the origin first, with the CDN not yet in front. Verify with curl.
  3. Start with everything bypassed except static assets. A CDN that caches nothing still terminates TLS closer to users and is not a failure.
  4. Add public dynamic routes one at a time, with short TTLs. Sixty seconds, then extend once you trust it.
  5. Run the leak test after every rule change, not just at the end.
  6. Watch origin request volume. It should drop noticeably. If it does not, something is bypassing that you think is caching.
  7. Keep a purge command to hand and know how long a full purge takes before you need it.

Common mistakes

  • Testing only in a logged-in browser, where cached-private-content bugs are invisible.
  • Setting proxy_cache_bypass without proxy_no_cache, protecting reads but not writes.
  • Vary: Cookie or Vary: User-Agent, which shatters the cache into near-unique entries.
  • Leaving tracking parameters in the cache key.
  • Configuring caching in the CDN dashboard only, so the policy is invisible to your code and absent from staging.
  • Trusting forwarded IP headers from any source rather than only the CDN’s ranges.
  • Using private where you needed no-store, or the reverse.
  • Caching everything on day one and finding the problems in production.

Best practices

  • Default to no caching, then allow specific routes. Opt-in beats opt-out when the failure mode is a data leak.
  • Own the policy at the origin so it travels with your code and exists in staging.
  • Use s-maxage for the edge and max-age for browsers. They are different problems.
  • Always set stale-if-error. It is free outage insurance.
  • Expose a cache status header and monitor hit ratio per route, not site-wide.
  • Build purge-on-publish into the application rather than relying on TTLs alone.
  • Make the leak test part of CI, so a future config change cannot reintroduce it quietly.

Frequently asked questions

Can a CDN cache dynamic pages at all?

Yes, and that is where most of the benefit is. Dynamic does not mean personalised. A blog post rendered from a database is identical for every anonymous visitor and can be cached at the edge for minutes. Only genuinely per-user content must bypass.

What is the difference between private and no-store?

private permits browser caching but forbids shared caches. no-store forbids writing the response to any cache at all. Use both for authenticated pages; use no-store alone for genuinely sensitive responses.

Why did my hit ratio collapse after adding a cookie banner?

Because the consent tool sets a cookie on every visitor and your CDN treats any cookie as a bypass signal, or you are varying on Cookie. Configure the CDN to ignore all cookies except the specific ones that indicate a session.

How do I verify private pages are not being cached?

Request the page with a real session cookie and confirm the cache status shows a bypass or miss, never a hit. Then request the same URL with no cookies and confirm the personalised content is absent. Do this after every cache rule change.

Should I cache API responses?

Public read-only endpoints, yes — with short TTLs and a cache key that includes whatever parameters affect the response. Anything requiring an Authorization header should be treated as private by default.

Do I still need caching at the origin?

Yes. The CDN protects you from repeat requests for the same URL; it does nothing for the first request, for uncacheable routes, or during a purge. Origin-level caching handles those.

Wrapping up

A CDN in front of a dynamic site is a classification problem wearing a performance costume. Sort your routes into public, private and static; express that at the origin with Cache-Control; make session cookies a hard bypass on both the read and write path; and keep tracking parameters out of the cache key.

Then test the way an anonymous visitor arrives, not the way you browse your own site. Two curl commands — one with a session, one without — catch the failure that matters, and they take about ten seconds. Run them every time you change a cache rule and the Monday email never arrives.


Want a CDN set up without the surprises?

I work with teams on edge caching for dynamic sites — route classification, cache headers that survive a redesign, purge-on-publish wired into the application, and the monitoring that tells you when hit ratio quietly drops.

If you would rather have this done carefully the first time, you can hire me on Upwork.

Leave a Reply