Friday, April 6, 2012

Browser Caching Using htaccess

Browser Caching Using htaccess
Setting up a browser cache for our webpages is very useful for large to medium size websites. It decreases the server load and increases the page load time by serving the cached webpages stored in visitors machine in form of cache.

What exactly it do ?
It stores the website data in visitors PC at the time they browse the website, And when they browse the webpage again it loads faster because its getting served via his own pc.

What is the benefit of doing this ?
- It reduces the server load and improves the server performance.
- It make the webpages load faster.

How to do this ?
Setting up browser cache is very simple. you can copy and paste the below code in your .htaccess file.

Code:
<IfModule mod_headers.c>
Header unset Pragma
FileETag None
Header unset ETag
<FilesMatch "\.(ico|pdf|jpg|jpeg|png|gif)$">
  Header set Cache-Control "max-age=864000, public, must-revalidate"
  Header unset Last-Modified
</FilesMatch>
<FilesMatch "\.(html|htm|xml|txt|xsl|css)$">
  Header set Cache-Control "max-age=7200, must-revalidate"
</FilesMatch>
</IfModule>

In the above code first we are declaring cache for images and pdf files for 864000 seconds.
And in the second one we are declaring cache for html, xml, xsl and css etc files for 7200 seconds.

Similarly we can add more extensions and file types for setting up cache for our webpages.
Please note that we need to specify the max-age in seconds, max-age should not be greater than 1years according to web standards.

Enjoy !

No comments:

Post a Comment