The Cache-Control
header is a fundamental HTTP header used to specify caching policies for both client requests and server responses. It plays a crucial role in controlling how, where, and for how long a resource is cached. Here is a detailed explanation of the Cache-Control
header:
Overview
The Cache-Control
header is a general header that specifies directives for caching mechanisms in both requests and responses. It provides fine-grained control over how resources are cached, ensuring efficient use of bandwidth, reduced latency, and decreased load on servers.
Syntax
The syntax for the Cache-Control
header is as follows:
Cache-Control: <directive>[, <directive>]*
Directives
The Cache-Control
header supports several directives, each serving a specific purpose:
- public: Indicates that the response can be cached by any cache, even if it is normally non-cacheable.
- private: Specifies that the response is intended for a single user and should not be stored by shared caches (e.g., CDNs).
- no-cache: The response can be stored by any cache, but it must be revalidated with the origin server before being used.
- no-store: The response must not be stored in any cache.
- max-age=: Specifies the maximum amount of time a resource is considered fresh. After this period, the cache must revalidate the resource with the origin server.
- s-maxage=: Similar to
max-age
, but specifically for shared caches. It overrides max-age
and the Expires
header when present.
- max-stale[=]: Indicates that the client is willing to accept a stale response. The optional time specifies the maximum staleness.
- min-fresh=: Indicates that the client wants a response that will remain fresh for at least the specified number of seconds.
- stale-while-revalidate=: Allows the client to use a stale response while asynchronously checking for a fresh one.
- stale-if-error=: Allows the client to use a stale response if the check for a fresh one fails.
- must-revalidate: The cache must revalidate the resource with the origin server once it becomes stale.
- proxy-revalidate: Similar to
must-revalidate
, but only for shared caches.
- immutable: Indicates that the response body will not change over time.
- **n...