How to leverage browser caching through htaccess. In this post, I’ll discuss, how to cache static contents (such as CSS, JS, Images etc) on a user browser through htaccess directives.
Before jump into the htaccess directives, Let’s understand what is caching and why it’s important for your website and blog.
What is Caching
In simple words, Caching is used to store static contents in a temporary storage, so that next time when visitor access the same content it will get served quickly through the cache.
Let’s say you visit any website, the files that your browser requests are stored in a temporary storage (known as browser cache). When you visit again on the same website it will load content from the cache so that it will serve quickly . Due to caching the downloading time for the same file is saved and the same webpage loads very quickly.
What is a browser caching ?
You can also minify CSS and JS files to reduce HTTP request.
How to Leverage Browser Caching through htaccess
We can use htaccess directives to cache these static files into the user browser.
htaccess is a configuration file used by web server. You can find this file on the root of your application directory.
To cache static contents add the following lines in your htaccess file.
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 application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
These above directives tell the browser to cache these files.
We need to specify in a cache headers that how long browsers should keep static contents (images, CSS, JS etc) stored locally. Of course, if you change any of these files, the server will tell the visitor’s browser to clear that cache.
All these things are done through Apache Mod expires headers.
If you have very high traffic website then you can speed up your website using Memcache .
How to check caching result
If you have written the above code in htaccess files then you enabled leverage browser caching. To see the result open the firebug in Mozilla or if you are using chrome then right click and go to inspect element. Then click on network. Then see whether it comes from cache or it loads every time you open the website.
If you have any suggestion, you can post a comment.