Agent Wranglers

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

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.