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.

 

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:
    1. The cache validity period (via the Expires header) which indicates how long a resource can be reused without contacting the server.
    2. Conditional validation (via the Last-Modified/If-Modified-Since headers) which allows checking if a resource has changed before re-downloading it.

 

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:

  1. Create or open the .htaccess file at the root of your site (usually in /web or /sites/domain.xyz).
  2. Add the configuration of the expires module:

    <IfModule mod_expires.c>
  3. 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.

  4. 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:

  1. 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.
  2. 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
  3. 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.

Has this FAQ been helpful?