How to Leverage Browser Caching with .htaccess

This tutorial explains how you add Expires headers to your .htaccess file. This will help you improve the performance of your website, based on Google’s recommended performance guidelines.

When a web browser displays your webpage it has to load several things like your logo, your CSS file, JavaScript, and other resources.

With Expires headers you tell visitor’s browser that the files you specify are not changing until after a certain time, for example a month.

This means that the browser doesn’t have to to get Images, CSS, JavaScript etc every time your visitor comes back to your site. .htaccess file is a quick & easy solution for  Leverage browser caching.

How to change browser caching on your site

It is done by adding some code to a file called .htaccess on your web host/server.

For those that are not tech savvy, modifying the .htaccess file might seem a little daunting. In reality, it is quite simple. For this tutorial, if you can cut and paste correctly, you should be worry-free.

Okay code time! The code below should be added to the top or bottom of your .htaccess file.

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
</IfModule>
## EXPIRES CACHING ##

Save the .htaccess file and then refresh your webpage.

How to set different caching times for different file types

You can see in the above code that there are time periods like “1 year” or “1 month”. These are associated with file types, as an example the above code states that a .jpg file (image) should be cached for a year. If you want to change that and say you want them only cached for a month you would simply replace “1 year” with “1 month”. The values above are pretty optimized for most webpages and blogs.