Speed Up Website By Caching Static Resources using Apache2 Cache Control (.htaccess)


Leverage browser caching is one of the use-and-it-works (must-have) techniques for hosting websites on Apache2 server. It is actually quite simple. You just have to enable the header module first by:

1
a2enmod headers
a2enmod headers

Make sure the module is enabled otherwise the following won’t work (you will get 500 internal server error).

Then, modify the .htaccess file for each websites (the root folder) and make sure you have Override All in apache2 mod-rewrite module configuration so that the .htaccess in sub directories inherit the changes from the root directory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 # 1 Month for all your static assets
 <FilesMatch ".(ico|pdf|bmp|vbs|flv|jpg|jpeg|png|gif|js|css|swf)$">
 Header set Cache-Control "max-age=2592000, public"
 </FilesMatch>
 
 # 1 DAY for rss feeds and robots
 <FilesMatch ".(xml|txt)$">
 Header set Cache-Control "max-age=86400, public, must-revalidate>
 </FilesMatch>
  
 # 8 HOURS for your real articles files
 <FilesMatch ".(html|htm)$">
 Header set Cache-Control "max-age=28800, must-revalidate>
 </FilesMatch>
 # 1 Month for all your static assets
 <FilesMatch ".(ico|pdf|bmp|vbs|flv|jpg|jpeg|png|gif|js|css|swf)$">
 Header set Cache-Control "max-age=2592000, public"
 </FilesMatch>
 
 # 1 DAY for rss feeds and robots
 <FilesMatch ".(xml|txt)$">
 Header set Cache-Control "max-age=86400, public, must-revalidate>
 </FilesMatch>
  
 # 8 HOURS for your real articles files
 <FilesMatch ".(html|htm)$">
 Header set Cache-Control "max-age=28800, must-revalidate>
 </FilesMatch>

The expiry date is measured in seconds and for each type of file, you can set a expiry time for the resources to be expired. So what the apache2 does is to tell your browser that the resources has not expired yet so instead of downloading from the server, why not use the not-expired existing file locally in the browser cache? This obviously will save time, improve page loading speed, and save the network bandwidth (reducing the load average/work load of the server).

Finally make sure you restart the apache2 server by

1
sudo /etc/init.d/apache2 restart
sudo /etc/init.d/apache2 restart

Or,

1
sudo service apache2 restart
sudo service apache2 restart

Try it, if you haven’t started yet, it works like a magic!

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
355 words
Last Post: How to Get a Email when System Load Average is High ? (Crontab)
Next Post: Linux BASH shell - Echo This if you get angry

The Permanent URL is: Speed Up Website By Caching Static Resources using Apache2 Cache Control (.htaccess)

One Response

Leave a Reply