The Cache-Control header field is used to store instructions (called directives) that inform the cache on what rules and guidelines to follow when caching data.
Cache in this context can be either a private cache (the client’s browser) or a public/shared cache such as a Proxy server or CDN.
Note: Cache-Control is a multi-value header, meaning it can accept multiple, comma-separated directives.
Let's say you have built a news site, and want to serve clients the latest news, with some specific rules in place:
Here's a header schema that satisfies these goals:
HTTP/1.1 200 OK
Date: Thu, 23 Sep 2023 12:00:00 GMT
Server: Apache
Content-Type: text/html; charset=utf-8
Content-Length: 8000
Cache-Control: max-age=600, stale-while-revalidate=60, stale-if-error=86400
max-age=600
: This directive tells your browser and intermediary caches that the content can be cached for up to 600 seconds (10 minutes). It's a typical caching duration for the front page.
stale-while-revalidate=60
: If the content becomes stale (older than 10 minutes), your browser and intermediary caches can still serve it for up to 60 seconds while they fetch a fresh copy in the background. This allows for a smoother user experience as the page doesn't wait for a complete revalidation.
stale-if-error=86400
: If there is an error (like a server issue) when trying to fetch fresh content, your browser and intermediary caches can serve the stale content for up to 86,400 seconds (24 hours). This ensures that even if something goes wrong, users can still access the news.
For specific information on each, see directives below (source: MDN):
Request | Response |
---|---|
max-age | max-age |
max-stale | - |
min-fresh | - |
- | s-maxage |
no-cache | no-cache |
no-store | no-store |
no-transform | no-transform |
only-if-cached | - |
- | must-revalidate |
- | proxy-revalidate |
- | must-understand |
- | private |
- | public |
- | immutable |
- | stale-while-revalidate |
stale-if-error | stale-if-error |