1000 FAQs, 500 tutorials and explanatory videos. Here, there are only solutions!
Use headers to optimize resource caching
This guide covers HTTP headers used to optimize resource caching and check if a resource has been modified since it was last retrieved by a client. Using these headers helps save bandwidth and speed up page loading by avoiding re-sending unchanged static resources.
Using the Expires Header
Configure caching headers using the mod_expires
module directives in the .htaccess
file at the root of your site directory (e.g., /web
or /sites/domain.xyz
):
- Open or create the
.htaccess
file at the root. Enter the following code:
<IfModule mod_expires.c>
Then enter your commands, e.g.:
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 define the expiry period for specific resources; in this example:
- HTML files are cached for one week
- JPEG images, CSS files, and JavaScript files are cached for one month
- You can adjust these values according to your needs
- These directives define the expiry period for specific resources; in this example:
End the addition with the closing tag:
</IfModule>
- Save the
.htaccess
file.
Using the If-Modified-Since Header
The HTTP header If-Modified-Since
is used by clients to check if a resource has been modified since it was last retrieved. If the resource has not changed, the server can respond with a 304 Not Modified
status code, avoiding the need to resend the full resource. This helps reduce bandwidth and speed up page loading.
To leverage the If-Modified-Since
header on your server:
Ensure your web server is configured to return the
Last-Modified
header when a resource is served; e.g., with Apache, this can be done via themod_headers
module:<IfModule mod_headers.c> Header set Last-Modified "expr=%{NOW}" </IfModule>
When the client makes a subsequent request for the same resource, it will include the
If-Modified-Since
header with the date of the last known modification:GET /resource HTTP/1.1 Host: www.example.com If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT
The server then compares the
If-Modified-Since
header date with the resource's last modification date; if the resource has not been modified since that date, the server returns a304 Not Modified
response:HTTP/1.1 304 Not Modified
- Otherwise, the server returns the updated resource with a
200 OK
status code.
By combining the Expires
and If-Modified-Since
headers, you can effectively optimize caching and modification checking of your resources, providing better performance for your users.