CDN Cache Rules Template
Template for CDN caching rules and edge behavior: cache keys, TTL by content type, query params, header forwarding, purge strategies and origin shield, with code examples.
Overview
A misconfigured CDN is worse than no CDN: stale pages served for hours, personalized content leaking between users, or a hit ratio so low the edge layer just adds latency. Get the cache rules right and all three go away.
This template is a copy-paste-ready policy for CDN caching: what goes into the cache key, which TTL each content type gets, which headers reach the origin, how to purge, and when an origin shield pays off. Replace the example values with yours and you’ve got CDN rules your team can follow — a proper setup typically cuts origin load by 80-95% and improves TTFB for every user. For the wider strategy, pair it with the CDN caching guide.
1. Cache Key Rules
1.1 Cache Key Components
Component | Include in key? | Reason
───────────────────┼──────────────────┼────────────────────────────
Path | Always | Primary cache identifier
Query parameters | Selective | Only cache-relevant params
HTTP method | Always (GET/HEAD)| Only cache safe methods
Headers | Selective | Vary by Accept, Accept-Encoding
Cookies | Never (default) | Breaks caching for auth
Protocol | No | HTTP/HTTPS serve same content
The cookies row is where most real-world breakage comes from: one analytics cookie and every visitor becomes a unique cache entry, collapsing your hit ratio to single digits. Strip cookies from static assets and only whitelist the ones your origin actually reads.
1.2 Query Parameter Rules
Parameter type | Example | Cache behavior
────────────────────┼──────────────────────┼──────────────────────────
Tracking params | ?utm_source=email | Ignore (strip from key)
Analytics params | ?ref=campaign | Ignore (strip from key)
Content params | ?page=2&sort=desc | Include in cache key
Format params | ?format=json | Include in cache key
Auth tokens | ?token=abc123 | Never cache (bypass CDN)
Session IDs | ?session=xyz | Never cache (bypass CDN)
1.3 Cloudflare Configuration
# Cloudflare Page Rules / Cache Rules
rules:
- name: "Ignore tracking parameters"
url: "*.example.com/*"
cache_key:
query_string:
include: ["page", "sort", "format", "category"]
exclude: ["utm_source", "utm_medium", "utm_campaign", "ref", "source"]
- name: "API responses - no cache"
url: "api.example.com/*"
cache:
enabled: false
- name: "Static assets - long cache"
url: "*.example.com/assets/*"
cache:
enabled: true
ttl: 31536000 # 1 year
browser_ttl: 31536000
2. TTL by Content Type
2.1 TTL Matrix
Content type | Edge TTL | Browser TTL | Revalidate
──────────────────────┼─────────────┼─────────────┼──────────────
HTML pages | 60-300s | 0 | Always
JSON API (public) | 30-60s | 0 | Always
JSON API (private) | 0 (no cache)| 0 | N/A
CSS/JS (versioned) | 31536000s | 31536000s | Never
Images (versioned) | 31536000s | 31536000s | Never
Images (unversioned) | 3600s | 3600s | Hourly
Fonts | 31536000s | 31536000s | Never
Sitemaps | 3600s | 0 | Hourly
Robots.txt | 3600s | 0 | Hourly
Redirects | 3600s | 3600s | Hourly
404 pages | 60s | 0 | Always
500 errors | 0 (no cache)| 0 | N/A
The whole matrix comes down to two rules of thumb. First, only give a long TTL to URLs that can’t change — that’s why versioned assets get a year while HTML gets minutes. Second, when in doubt, keep the edge TTL short and let stale-while-revalidate (or a soft purge) hide the refresh from users.
2.2 HTTP Headers Configuration
# Nginx origin headers
# HTML pages — short edge cache, revalidate always
location / {
add_header Cache-Control "public, max-age=0, s-maxage=300";
add_header Vary "Accept-Encoding";
}
# Static assets with versioned URLs — immutable
location /assets/ {
add_header Cache-Control "public, max-age=31536000, immutable";
}
# API endpoints — no CDN cache
location /api/ {
add_header Cache-Control "no-store, no-cache, must-revalidate";
add_header CDN-Cache-Control "no-store";
}
# Sitemaps — hourly cache
location /sitemap.xml {
add_header Cache-Control "public, max-age=0, s-maxage=3600";
}
When the origin hiccups, stale-while-revalidate and stale-if-error buy you grace: the edge keeps serving the last good copy while it quietly refetches. Add them to HTML responses — a 60-300s stale window covers most transient origin failures without anyone noticing.
3. Header Forwarding
3.1 Forwarding Rules
Header | Forward to origin? | Include in cache key? | Reason
────────────────────┼────────────────────┼───────────────────────┼──────────────
Authorization | No (strip at edge) | No | Auth at origin
Accept | Yes | Yes | Content negotiation
Accept-Encoding | Yes | Yes | Compression
Accept-Language | Yes | Yes | i18n variants
User-Agent | No (strip at edge) | No | Breaks caching
Cookie | Conditional | No | Auth sessions
X-Forwarded-For | Yes | No | IP logging
X-Request-ID | Yes | No | Tracing
Watch the Accept-Language row before enabling it in the key: browsers send dozens of variants (en-US, en-GB;q=0.9, es-ES,es;q=0.8,en;q=0.6…). Normalize to your supported locales at the edge first — otherwise every header variant fragments the cache.
3.2 Cloudflare Header Rules
# Forward selected headers to origin, strip others
header_rules:
- name: "Strip User-Agent for caching"
action: remove
header: User-Agent
direction: request
- name: "Forward Accept-Language for i18n"
action: set
header: Accept-Language
cache_key: true
- name: "Strip cookies for static assets"
action: remove
header: Cookie
match: "/assets/*"
4. Purge Strategies
4.1 Purge Methods
Method | Scope | Speed | Use when
────────────────────┼────────────────────┼────────────┼──────────────────────
Purge everything | All cached content | 30-60s | Deployments, emergencies
Purge by URL | Single URL | 5-10s | Content update
Purge by tag | Group of URLs | 10-30s | Category/product update
Purge by prefix | Path prefix | 10-30s | Section update
Purge by host | Entire domain | 30-60s | Domain migration
Soft purge | Mark as stale | Instant | Graceful refresh
4.2 Purge API Examples
# Cloudflare purge by URL
import requests
def purge_urls(zone_id: str, api_token: str, urls: list):
response = requests.post(
f"https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache",
headers={
"Authorization": f"Bearer {api_token}",
"Content-Type": "application/json",
},
json={"files": urls},
)
return response.json()
# Purge by cache tag (Cloudflare Enterprise)
def purge_by_tag(zone_id: str, api_token: str, tags: list):
response = requests.post(
f"https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache",
headers={
"Authorization": f"Bearer {api_token}",
"Content-Type": "application/json",
},
json={"tags": tags},
)
return response.json()
# Usage: purge all product pages after catalog update
purge_by_tag("zone123", "token456", ["products", "catalog"])
4.3 Automated Purge on Deploy
# GitHub Actions post-deploy purge
import os
import requests
def purge_after_deploy():
zone_id = os.environ["CLOUDFLARE_ZONE_ID"]
api_token = os.environ["CLOUDFLARE_API_TOKEN"]
# Purge everything after deployment
response = requests.post(
f"https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache",
headers={"Authorization": f"Bearer {api_token}"},
json={"purge_everything": True},
)
if response.json()["success"]:
print("CDN purged successfully after deployment")
else:
print(f"Purge failed: {response.json()['errors']}")
4.4 Verifying a Purge
The API response alone isn’t proof — check the resource itself:
# cf-cache-status should flip to MISS/EXPIRED right after a purge,
# then HIT once the edge re-warms the entry
curl -sI https://example.com/assets/app.js | grep -i cf-cache-status
If the status stays HIT minutes after a purge, the URL you purged doesn’t match the cache key — usually a query string or trailing-slash difference. Compare the purged URL character-for-character with the one in the response headers.
5. Origin Shield
5.1 Origin Shield Configuration
# Cloudflare origin shield
origin_shield:
enabled: true
region: "us-east-1" # Primary shield location
# Benefits:
# - Reduces origin requests by 90%+ (shield caches for all edges)
# - Protects origin from traffic spikes
# - Single connection pool to origin
# When to use:
# - Origin is a single server (no load balancer)
# - Traffic > 100 req/s
# - Origin is in a single region
5.2 When an Origin Shield Doesn’t Pay Off
Skip the shield if your origin already sits behind a load balancer across regions, or if your traffic is low enough that a single shared cache node saves you nothing. Each extra tier adds latency to cache misses, so on a quiet site the shield costs more than it protects. Measure origin hit rate before and after enabling it — if origin requests don’t drop clearly, turn it off.
5.3 Multi-Tier Caching
Request flow:
User → Edge cache (nearest PoP) → Origin shield → Origin server
Edge cache miss rate: ~5-10% of requests reach origin shield
Shield cache miss rate: ~1-5% of requests reach origin
Total origin load: ~0.5-1% of total requests
6. Monitoring
6.1 CDN Metrics
Metric | Source | Alert threshold
──────────────────────────┼─────────────────┼──────────────────
Cache hit ratio | CDN analytics | < 90%
Origin requests | CDN analytics | > 10% of total
Edge response time p95 | CDN analytics | > 100ms
Origin response time p95 | Origin logs | > 500ms
Purge operations | CDN API | > 10/hour
Bandwidth (edge) | CDN analytics | Monthly budget
Cache size | CDN analytics | Near plan limit
6.2 Monitoring Script
def check_cdn_health(zone_id: str, api_token: str):
response = requests.get(
f"https://api.cloudflare.com/client/v4/zones/{zone_id}/analytics/dashboard",
headers={"Authorization": f"Bearer {api_token}"},
params={"since": "-1440", "until": "now"},
)
data = response.json()["result"]["totals"]
total_requests = data["requests"]["all"]
cached_requests = data["requests"]["cached"]
hit_ratio = (cached_requests / total_requests * 100) if total_requests else 0
print(f"CDN Health Report:")
print(f" Total requests: {total_requests:,}")
print(f" Cached requests: {cached_requests:,}")
print(f" Hit ratio: {hit_ratio:.1f}%")
print(f" Bandwidth: {data['bandwidth']['all'] / 1e9:.1f} GB")
if hit_ratio < 90:
print("ALERT: CDN hit ratio below 90%")
return hit_ratio
6.3 Weekly Review
Once a week, check three things: hit ratio trend (drops usually mean a deploy broke a cache key), the top-10 uncached URLs (they’re your next rules), and purge volume (frequent full purges mean your tags are too coarse). Log the numbers in the same place each week — a sliding hit ratio is the first symptom of a caching regression nobody reported.
7. Debugging a Broken Rule
When a page misbehaves, the response headers tell you which rule fired. Check these before touching config:
# What the edge actually did with your request
curl -sI https://example.com/page | grep -iE "cf-cache-status|age|cache-control|x-cache"
Header | What it tells you
────────────────────┼────────────────────────────────────────────────
cf-cache-status | HIT / MISS / EXPIRED / BYPASS / DYNAMIC (Cloudflare)
x-cache | Hit from cloudfront / Error from cloudfront (CloudFront)
age | Seconds the object has sat in the edge cache
cache-control | The directives your origin sent
vary | Which headers split the cache entry
The three failure patterns you’ll meet most:
- BYPASS or DYNAMIC on a cacheable URL — a
Set-CookieorAuthorizationheader is reaching the edge. Strip it for that path. - HIT on the wrong content — a query param or
Accept-Languagevariant is splitting the key; normalize it, or a stale purge left the old entry (soft purge again and re-checkage). - MISS that should be HIT — the rule ordering picked the wrong match. Most CDNs evaluate rules top-down, so a broad
*rule placed above a specific one swallows everything.
8. Concrete Cases
8.1 SPA or CSR App
# SPA: cache the shell long, the HTML entry point barely
rules:
- name: "Versioned bundle assets"
url: "*.example.com/static/*"
cache: { enabled: true, ttl: 31536000, browser_ttl: 31536000 }
- name: "index.html — always fresh"
url: "*.example.com/index.html"
cache: { enabled: true, ttl: 60, browser_ttl: 0 }
The pattern is always the same: fingerprinted files get a year, the entry document gets a minute. If your bundler doesn’t emit content hashes, fix that before tuning the CDN — unversioned /static/app.js is the classic stale-JS bug.
8.2 Mixed Public and Authenticated API
rules:
- name: "Public catalog API"
url: "api.example.com/catalog/*"
cache: { enabled: true, ttl: 60 }
- name: "User endpoints — never cache"
url: "api.example.com/me/*"
cache: { enabled: false }
headers: { strip_request: ["Cookie", "Authorization"] }
The rule that matters is the negative one: anything under a user path gets no-store and strips auth headers at the edge, so a cached public response can never leak into a private context. Leaks between users are the worst CDN bug there is — one mis-scoped rule and a customer’s profile page becomes everyone’s cached copy.
8.3 GraphQL Endpoint
# POST bodies can't go in the cache key, so cache only GET/persisted queries
rules:
- name: "Persisted GraphQL queries"
url: "api.example.com/graphql"
cache:
enabled: true
ttl: 60
cache_key: { query_string: ["id", "variables"] }
GraphQL caches poorly by default because everything POSTs to one URL. If you use persisted queries (a hash or operation ID in the query string), that ID can join the cache key and the CDN becomes useful again. See the GraphQL caching guide for the full setup.
8.4 Cache Poisoning
Any header, cookie or parameter that reaches the origin and bounces back into the response is a poisoning vector if it also lands in the cache key — or worse, if it doesn’t. An attacker crafts a URL like ?cb=<script> that reflects into the page; the edge then happily serves that poisoned copy to everyone until it expires.
The defense is boring and absolute: strip from the cache key anything the response reflects, and normalize what remains. Never reflect query params or headers in output without encoding, and run a quick negative test — request https://example.com/?poison=test123 and check the HTML isn’t embedding test123 before you trust the key config.
9. Alternative Provider: AWS CloudFront
The concepts map one-to-one; the configuration just looks different. CloudFront organizes behavior per path pattern:
// CloudFront behavior for /assets/* — long immutable cache
{
"PathPattern": "/assets/*",
"CachePolicyId": "managed-CachingOptimized",
"OriginRequestPolicyId": "managed-AllViewerExceptHostHeader",
"TTL": { "DefaultTTL": 31536000, "MaxTTL": 31536000 },
"Compress": true
}
// Behavior for /api/* — bypass cache, forward auth
{
"PathPattern": "/api/*",
"CachePolicyId": "managed-CachingDisabled",
"OriginRequestPolicyId": "managed-AllViewer"
}
Translation table if you’re coming from Cloudflare: cache_key → Cache Policy’s key settings, page rule → Behavior, origin shield → Origin Shield (yes, same name — CloudFront added it in 2020), purge → Invalidation (/api/* path pattern, $0.005 per path after the free batch). See the CloudFront cache behavior docs for the full field list.
10. Cache Rules Checklist
- Cookies stripped from static assets and public pages
- Only cache-relevant query params in the key (no
utm_*, tokens, session IDs) - Versioned assets at 1-year TTL with
immutable; HTML at 60-300s edge + 0 browser - Auth/user paths explicitly
no-storeand stripped at the edge -
stale-while-revalidate+stale-if-erroron HTML - Purge automated in deploy (tag or soft purge, not purge-everything)
- Hit ratio monitored weekly with an alert under 90%
- Rule order checked — specific paths before broad wildcards
- Rules themselves versioned — keep the config in git so a bad rule can be rolled back like code
Keep this file in version control next to the deploy that uses it. CDN rules change less often than application code but break just as hard when they do — a config diff you can git blame beats a settings page somebody edited by hand three months ago and forgot. Roll out rule changes the way you roll out code: stage them on a small path first, watch the hit ratio and cf-cache-status for a day, then widen the scope. Nobody remembers the deploy that broke caching for a quiet path; everyone remembers the one that took down /. When in doubt, leave a rule out — a conservative cache is a cache you can explain in one breath to whoever gets paged.
See Also
- Complete Guide to CDN Caching Strategy
- CDN Cache Invalidation Strategies and Patterns
- Complete Guide to GraphQL Caching
- Complete Guide to Redis Caching Strategies
- Read-Through Cache Pattern
- Cloudflare Cache documentation: official reference for cache keys, TTLs and purge API.
- Companion code: the cdn-cache-rules-template companion repo packages the purge script and the nginx headers config.
Frequently Asked Questions
Should I cache HTML pages at the CDN?
Yes — a short edge TTL (60-300 seconds) plus max-age=0 on the browser side. This reduces origin load while ensuring users see fresh content within the edge TTL. Cache tags or purge-by-URL let you invalidate specific pages as soon as content changes. For personalized pages (user dashboard, settings), bypass CDN caching entirely with a Cache-Control: no-store header.
How do I handle cache busting for versioned assets?
Put a content hash in asset filenames (app.a1b2c3d4.js) and serve them as Cache-Control: public, max-age=31536000, immutable. When the file changes, the hash changes, creating a new URL that the CDN caches fresh. Never purge versioned assets — they're immutable. The old versions simply fall out of the CDN cache through LRU eviction. This eliminates the need for purge operations on asset updates.
What query parameters should I include in the cache key?
Only include parameters that change the response content. Common cache-relevant parameters: page, sort, filter, category, format, view. Always exclude tracking parameters (utm_*, ref, source), analytics parameters, and session tokens. Including irrelevant parameters in the cache key reduces hit ratio because each parameter variant creates a separate cache entry.
How do I purge cached content after a deployment?
Purge-by-tag gives you granular control; purge-everything is the blunt-but-simple option. For zero-downtime deployments, use soft purge (marks content as stale rather than deleting). The CDN serves stale content while fetching fresh content from the origin in the background. This prevents origin spikes during purge. Automate purging in your CI/CD pipeline as a post-deploy step.
What is the difference between edge TTL and browser TTL?
The edge TTL (s-maxage or CDN-Cache-Control) decides how long the CDN keeps the response around. Browser TTL (max-age) controls how long the user's browser caches the response. For HTML pages, set edge TTL to 300s and browser TTL to 0 (always revalidate). For versioned assets, set both to 1 year. The edge TTL should always be shorter than or equal to the browser TTL for content that changes.
Related Resources
Cache Strategy Decision Template
Fill-in template for choosing and documenting a cache strategy per service: decision matrix, TTL rules, invalidation plan, and rationale record.
DocCache Warmup Runbook
Operational runbook for warming caches after deploys, restarts and incidents: identify hot keys, preload by priority, verify hit ratio and roll back safely.
DocCache Eviction Policy Template
Template for documenting cache eviction rules per cache layer: LRU, LFU, TTL, FIFO, random eviction. Includes policy selection matrix, per-layer configuration, memory limits, and monitoring rules with code examples.
GuideComplete Guide to CDN Caching Strategy
CDN caching for web apps and APIs: edge caching, cache keys, headers, invalidation, surrogate keys, stale strategies and multi-CDN setups.
PatternRead-Through Cache Pattern
A transparent cache layer that intercepts read requests, fetches from the data source on miss, and populates the cache automatically.