Base de conhecimento
1000 perguntas frequentes, 500 tutoriais e vídeos explicativos. Aqui, você encontra apenas soluções!
Use headers to optimize resource caching
This guide explains how to optimize the caching of web resources using HTTP headers.
Preamble
- A good caching strategy can significantly improve the performance of your site 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 checking 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 specifying a duration during which the browser can directly reuse resources from its local cache. Here is how to configure it in your .htaccess file:
- Create or open the
.htaccessfile at the root of your site (usually in/webor/sites/domain.xyz). Add the configuration of 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 will be kept for one 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 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-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 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 para esta FAQ: https://faq.infomaniak.com/1282
Esta seção de perguntas frequentes foi útil?