Expires headers are a method that allows you to indicate when a certain resource should expire and no longer be retrieved from the server. You direct the visitor’s browser to save a local copy of the resource by specifying an expiration date. When the user returns to your website, the browser can receive the resource from the cache rather than making another server request.
When it comes to optimizing website performance, one essential aspect to consider is caching. By adding expires headers to your .htaccess file, you can control how long specific resources are cached in a visitor’s browser. This reduces server strain, bandwidth consumption, and page load times for repeat users dramatically.
One of the most typical mistakes we encounter while performance testing our websites on GTmetrix is ‘add Expires headers’. By including expires headers in the .htaccess file, you may configure cache-control headers and expiration times for specific file types.
How to add expires headers using the htaccess file?
Create a new text file and name it .htaccess – If you already have an .htaccess file in your website’s root directory, proceed to the next step.
Before adding expires headers, ensure that the mod_expires module is enabled on your server. You can check this by looking for the following line in your server configuration file (httpd.conf)
If you have root access and confident to proceed, If the ( # ) is present, you’ll need to enable the module by uncommenting the line ( Remove the # ) and restarting your web server.
#LoadModule expires_module modules/mod_expires.so
- Note: The .htaccess file may be hidden, you may have to use an FTP client or cPanel file manager to enable the “Show Hidden Files” option in settings.
- Add Expires Headers Inside the .htaccess file, add the following code to enable expires headers.
# Set expiration for specific file types
ExpiresByType text/html "access plus 1 week"
ExpiresByType image/jpeg "access plus 2 weeks"
ExpiresByType text/css "access plus 2 weeks"
ExpiresByType image/png "access plus 2 weeks"
# Set default expiration for all other file types
ExpiresDefault "access plus 1 month"
The access plus 1 month directive states that unmentioned resources will be cached for one month. This figure can be changed to suit your needs. Once you’ve included the necessary expires headers, save the .htaccess file and upload it to your website’s root directory or the specific subdirectory where you want the caching rules to apply.
Check that the expires headers are operating properly after uploading the .htaccess file. You may examine the response headers for the resources on your website using online tools or browser developer tools.
By using expires headers, you may use browser caching to boost the performance of your website. This method decreases server load, and improves user experience. To leverage, follow the above-mentioned step-by-step procedure.