1000 FAQs, 500 tutorials and explanatory videos. Here, there are only solutions!
Use headers to optimize resource caching
This guide explains how to optimize the cache of web resources through HTTP headers.
Preamble
- A good cache strategy makes it possible to significantly improve the performance of your site by avoiding unnecessary retransmission of unchanged files.
- The web cache is based on two complementary mechanisms:
- The duration of the cache (via the header)
Expires
) which indicates how long a resource can be reused without contacting the server. - Conditional validation (via headers)
Last-Modified
/If-Modified-Since
) which allows to check whether a resource has changed before redownloading.
- The duration of the cache (via the header)
Configuring the cache duration with Expires
The header Expires
allows you to specify a time period during which the browser can reuse resources directly from its local cache. Here's how to configure it in your file .htaccess
:
- Create or open the file
.htaccess
at the root of your site (usually in/web
or/sites/domain.xyz
). Add module configuration
expires
:<IfModule mod_expires.c>
Define the appropriate cache times for each resource type:
ExpiresActive On ExpiresByType text/html "access plus 1 week" ExpiresByType image/jpeg "access plus 1 month" ExpiresByType text/css "access plus 1 month" ExpiresByType application/javascript "access plus 1 month"
These guidelines mean that:
- HTML pages will be cached for a week.
- JPEG images, CSS files and JavaScript will be kept for a month.
Adapt these times according to the frequency of updating your resources.
Close the configuration section:
</IfModule>
Conditional validation with Last-Modified
Even when a resource has expired in the cache, it is not always necessary to download it completely. The conditional validation mechanism allows the browser to check if its cached version is still up to date. This process works as follows:
- Server automatically sends a header
Last-Modified
with each resource, indicating its date of last modification.- Apache manages this natively for static files - no additional configuration is required.
When the browser asks for the resource again, it sends a header
If-Modified-Since
containing the date it has in cache:GET /resource HTTP/1.1 Host: www.example.com If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT
- The server compares this date with the actual file modification date:
- If the file has not changed, it simply returns a code
304 Not Modified
, saving bandwidth. - If the file has been modified, it returns the new version with a code
200 OK
.
- If the file has not changed, it simply returns a code