The Expires
header is part of the HTTP/1.1 specification and is used to indicate the maximum age of a resource in cache. It is a response header, meaning that it is sent by the server to the client. The client (usually a browser) can then use this information to determine if the cached resource is still fresh or if it needs to request a new copy from the server.
The Expires
header is defined as follows:
Expires: <http-date>
The <http-date>
is a date string in the format specified by RFC 7231, which is a subset of the ISO 8601 date format.
Use Cases
The main use case for the Expires
header is to improve the performance of web applications by reducing the need for clients to request resources from the server. By specifying an expiration date and time, the server can inform the client that a resource is still valid, thus allowing the client to use the cached copy instead of requesting a new one.
This can lead to significant performance improvements, especially for static resources like images, stylesheets, and scripts, which do not change frequently.
Examples
Response Header with Expires
In this example, the server sends an Expires
header with a value of Wed, 21 Oct 2021 07:28:00 GMT
. This indicates that the resource will be considered stale after that date and time.
HTTP/1.1 200 OK
Content-Type: image/jpeg
Content-Length: 12345
Expires: Wed, 21 Oct 2023 07:28:00 GMT
The client receiving this response can cache the resource and use the cached copy until the specified expiration date and time.
Request Header with If-Modified-Since
When a client has a cached copy of a resource and wants to check if it is still fresh, it can send an If-Modified-Since
header along with the request. This header contains the date and time of the cached resource’s last modification.
GET /image.jpg HTTP/1.1
Host: example.com
If-Modified-Since: Tue, 20 Oct 2023 07:28:00 GMT
The server can then compare the If-Modified-Since
header value with the actual last modification date of the resource. If the resource has not been modified since the specified date, the server can return a 304 Not Modified
status, indicating that the client can continue to use the cached copy.
HTTP/1.1 304 Not Modified
Date: Wed, 21 Oct 2023 07:28:00 GMT
By using the Expires
header, you can improve the performance of your applications by reducing the need for clients to request resources from the server.