Knowledge base
1000 FAQs, 500 tutorials and instructional videos. Here, there are only solutions!
Use headers to optimize resource caching
This guide explains how to optimize the caching of web resources using HTTP headers.
Introduction
- A good caching strategy can significantly improve your website's performance by avoiding the unnecessary retransmission of unchanged files.
- Web caching relies on two complementary mechanisms:
- The cache validity period (via the
Expiresheader), which indicates how long a resource can be reused without contacting the server. - Conditional validation (via the
Last-Modified/If-Modified-Sinceheaders), which allows you to check if a resource has changed before re-downloading it.
- The cache validity period (via the
Configuring the 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
.htaccessfile in the root directory of your website (usually in/webor/sites/domain.xyz). Add the configuration for the
expiresmodule:<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 files will be cached for one month.
Adjust these durations according to the frequency with which your resources are updated.
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 again. 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-Modifiedheader 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-Sinceheader containing the date it has in its 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 Modifiedcode, thus saving bandwidth. - If the file has been modified, it returns the new version with a
200 OKcode.
- If the file has not changed, it simply returns a
Link to this FAQ: https://faq.infomaniak.com/1282
Has this FAQ been helpful?