1000 FAQs, 500 tutorials and explanatory videos. Here, there are only solutions!
Use headers to optimize resource caching
This guide explains how to optimize web resource caching using HTTP headers.
Preamble
- A good caching strategy can significantly improve your site's performance by avoiding the unnecessary retransmission of unchanged files.
- Web caching relies on two complementary mechanisms:
- The cache validity duration (via the
Expires
header) which indicates how long a resource can be reused without contacting the server. - Conditional validation (via the
Last-Modified
/If-Modified-Since
headers) which allows checking if a resource has changed before re-downloading it.
- The cache validity duration (via the
Configuring cache duration with Expires
The Expires
header allows specifying a duration during which the browser can directly reuse resources from its local cache. Here's how to configure it in your .htaccess
file:
- Create or open the
.htaccess
file at the root of your site (usually in/web
or/sites/domain.xyz
). Add the configuration of the
expires
module:<IfModule mod_expires.c>
Define the appropriate cache durations for each type of resource:
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 directives mean that:
- HTML pages will be cached for one week.
- JPEG images, CSS files, and JavaScript will be kept for one month.
Adjust these durations according to the update frequency of 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 completely re-download it. The conditional validation mechanism allows the browser to check if its cached version is still up-to-date. This process works as follows:
- The server automatically sends a
Last-Modified
header with each resource, indicating its last modification date.- Apache handles this natively for static files - no additional configuration is required.
When the browser requests the resource again, it sends an
If-Modified-Since
header 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
304 Not Modified
code, thus saving bandwidth. - If the file has been modified, it returns the new version with a
200 OK
code.
- If the file has not changed, it simply returns a