Cache Control Headers


Cache headers are fundamental components in controlling how application resources are cached, both by browsers (client cache) and by intermediary proxies (like Peqi, for example). Proper configuration of these headers can result in significant improvements in page loading speed, bandwidth efficiency, and the overall user experience. Let's explore the most common cache headers and how they are used to control caching behavior.

Cache-Control

The Cache-Control header is one of the most powerful and flexible for cache control. It allows specifying directives for both private (browsers) and public (proxies and CDNs) caches.

max-age=[seconds]: specifies the maximum time a resource is considered fresh.
no-cache: forces the cache to revalidate the resource with the server before serving the cached version.
no-store: instructs the cache not to store a copy of the resource under any circumstances.
public: indicates that the response can be stored by any cache, even if the response is normally non-cacheable.
private: the response is intended for a single user and should not be stored by shared caches.
must-revalidate: the cache must revalidate an expired resource before using it, ensuring the content is not outdated.

Expires

The Expires header is used to set a specific date/time after which the response is considered stale. If the content is static and does not change frequently, this header can be a simple way to control caching.

ETag

The ETag header provides a unique identifier for a version of a resource. This allows for an efficient validation method: the client can send an If-None-Match header with the ETag on subsequent requests. If the resource has not changed, the server can respond with a 304 (Not Modified) status, indicating that the cache can be reused.

Last-Modified

Similar to the ETag, the Last-Modified header indicates the last time the resource was modified. Clients can send an If-Modified-Since header on subsequent requests. If the resource has not been modified since then, the server responds with 304, allowing the cache to be used.

Pragma

The Pragma header is an HTTP/1.0 header, generally used only as a fallback for compatibility with HTTP/1.0 caches where the Cache-Control header is not supported. The Pragma: no-cache value is equivalent to Cache-Control: no-cache.

Vary

The Vary header informs the cache that the requested response is variable based on one or more request headers. For example, Vary: User-Agent indicates that a different response may be stored and served based on the user agent making the request.

Related Articles