How to Leverage Browser Caching

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.

htaccess Tutorial

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.

If you have very high traffic website then definitely you go for in-memory caching such as Memcache , Redis etc.

What is a browser caching ?

When a webpage loads into the browser, several things download in a background such as CSS, Javascript, images etc. All these are static contents. If you cache these static contents ( such as CSS, Javascript, Images etc) into the user browser, then next time when user access the same web page then it will load very quickly as all the static contents are served from cache.

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.

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.

caching_result

If you have any suggestion, you can post a comment.

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.