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.
Introduction
- A good caching strategy significantly improves 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
Configuration of cache duration with Expires
The Expires
header allows you to specify 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 for the
expires
module:<IfModule mod_expires.c>
Set 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 files will be kept for a month.
Adjust these durations according to the frequency of updates to 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 redownload 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 a
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