HTTP Cache-Control Header
HTTP caching is a mechanism that helps to improve the performance of web applications by storing copies of responses (such as web pages or resources like images, scripts, etc.) in intermediate storage locations (like browsers, proxy servers, and content delivery networks). This reduces the need for repeated requests to the origin server, which can improve load times and reduce server load.
HTTP caching can be controlled on both the request (client-side) and response (server-side) by the header fields of the HTTP request and/or response.
Cache-Control Header
This header is used to specify caching directives and is the most important header when it comes to controlling how and for how long responses are cached.
Common directives
- public: The response can be cached by both browsers and intermediary caches (like CDNs or proxies).
- private: The response is intended for a single user and should not be cached by shared caches (like CDNs).
- no-cache: The response must not be used from cache without revalidation (although it can still be stored in the cache).
- no-store: The response should not be stored in any cache (e.g., sensitive data like passwords).
- max-age: Specifies the maximum amount of time (in seconds) that the response is considered fresh. For example, max-age=3600 means the response is fresh for 1 hour.
- s-maxage: Similar to max-age, but applies only to shared caches (e.g., CDNs or proxies).
- must-revalidate: When the response becomes stale, caches must verify the response with the origin server before serving it.
Example
Suppose we want the user to be served a cached version of the resource on subsequent requests for up to 3,600 seconds after that resource was first requested from the server.
Cache-control takes a relative amount of time. There can be many comma-separated values for this field. We have to set the maximum age to 3600. max-age is set in seconds.
Cache-Control “max-age=3600,public”