How to Leverage browser caching in Apache

This tutorial teaches how to leverage browser caching using .htaccess.

To speed up the navigation through your website you have to tell the browser to cache all static data. All you need to do is to modify .htaccess config in the website document root directory. Let's get started.

Getting rid of ETag

First of all, we need to disable ETag header since we are going to use Expires. ETag technology is known as slow and problematic - even YSlow complains about it.

Add to .htaccess:

Header unset Pragma
FileETag None
Header unset ETag

Setting Cache-Control and Expires headers

Add to .htaccess:

<FilesMatch "\.(ico|jpg|jpeg|png|gif|js|css|swf|pdf|flv|mp3)$">
<IfModule mod_expires.c>
 ExpiresActive on
 ExpiresDefault "access plus 14 days"
 Header set Cache-Control "public"
</IfModule>
</FilesMatch>
<FilesMatch "\.(html|htm|xml|txt|xsl)$">
 Header set Cache-Control "max-age=7200, must-revalidate"
</FilesMatch>

What this does is adding far future expires header (make sure mod_expires is loaded in your apache config if you have problems) to your static content (images, js, css, etc).

This will improve your Page Speed and YSlow scores and increase website speed.
The next thing you should do is to enable gzip compression on Apache.






  1. Taswir Haider
    2013-03-18 18:14:19
    Hi, I used your above codes in .htaccess file and checked the site thereafter but it seems that the speed has got down to 83 from 86 as per Google PageSpeed and Pingdom.
    
    My site is http://www.thetopblogger.com.
    And email ID is: -hidden-
    
    Could you please help me in "Leverage Browser Caching" as this is my #1 problem for long time.
    
    Would be glad to receive your help and cooperation in this regard.
  1. kalam
    2016-10-08 11:08:42
    Out of 4 Nearly 2 sec of loading speed is reduce by using the above code.
    Most usefull 
  1. bjordanov.com
    2016-03-11 21:53:11
    Super useful, worked for me, thanks!

Got a comment?

captcha =

Categories

  1. System (20)
    1. FreeBSD (5)
    2. Linux (9)
  2. Email (2)
  3. DNS (2)
  4. Databases (1)
  5. WebServer (27)
 
Copyright © 2012-2015 HowToUnix - *nix Howtos and Tutorials
All Rights Reserved.