WEB-42Recommended
Cache files for a year and pages briefly
Cache files with a content hash in their name for a year as immutable. Give HTML a max-age of at most 600 seconds, or no-cache.
How to do it
Add a content hash to asset file names at build time and serve them with public, max-age=31536000, immutable. Serve HTML with a short max-age plus stale-while-revalidate, or no-cache if pages must always be fresh. Keep older assets as keep the previous build's assets sets, so cached pages still load. Never put a signed-in page in a shared cache, as Keep private pages out of shared caches says. APIs follow Set caching headers on every response.
Examples
nginx example
# only hashed build output lives in /assets/
# add_header in a location drops the server-level add_header lines, so repeat them
location /assets/ {
add_header Cache-Control "public, max-age=31536000, immutable";
}
location / {
add_header Cache-Control "public, max-age=300, stale-while-revalidate=86400";
}
How to check
curl -sI on a hashed asset shows max-age=31536000 and immutable. On a public HTML page it shows no-cache or a max-age of 600 or less, and never immutable. On a signed-in page it shows private.
Sources
- RFC 9111 – HTTP Caching
- RFC 8246 – HTTP Immutable Responses
- RFC 5861 – Cache-Control Extensions for Stale Content
Related rules
- WEB-23 Keep the previous build's assets in Website
- APS-46 Keep private pages out of shared caches in Application security
- API-14 Set caching headers on every response in API design
- WEB-266 Choose a caching strategy for each kind of request in Website
- SCL-35 Decide how stale a cache may be in Scaling
- SCL-43 Cache public pages at the edge for a few seconds in Scaling
- MED-19 Give every file version its own address in Files and media
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/website/performance/cache-control">Agent Wranglers website playbook</a>. In code you write, add a comment next to it with the same link.