htaccess Essential Cache Script

by Hiroshi on March 8, 2013

in htaccess

Recently I noticed that a caching plugin was creating problem with the WordPress blog. Instead of performance upgrade, my blog was becoming less responsive. I had to turn it off and change the caching plugin. That cache plugin installed cache code in .htaccess file as well. I had to remove it too. I have compiled my own .htaccess cache code that can be used for any website to update the website performance. It turns off unnecessary elements e.g ETags and Last-Modified headers. It also checks the file type and implements necessary expiry time and cache age for that file. For example: How much do you have to change your .ico file? Never! Right? Well almost never. So why load a fresh copy of .ico file again and again when it can be cached?

Here is the code. Copy and paste it in your .htaccess file and you will see a performance upgrade in website loading time. This is not just for PHP websites or WordPress blogs. It can be used for any type of website.

<filesMatch ".(ico|pdf|flv|jpg|jpeg|png|gif|js|css)$">
Header unset Last-Modified
</filesMatch>
 
Header unset ETag
FileETag None
 
# Turn on Expires and set default to 0
ExpiresActive On
ExpiresDefault A0
 
# Set up caching on media files for 1 year (forever?)
<FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav)$">
ExpiresDefault A29030400
Header append Cache-Control "public"
</FilesMatch>
 
# Set up caching on media files for 1 week
<FilesMatch "\.(gif|jpg|jpeg|png|swf)$">
ExpiresDefault A604800
Header append Cache-Control "public"
</FilesMatch>
 
# Set up 2 Hour caching on commonly updated files
<FilesMatch "\.(xml|txt|html|js|css)$">
ExpiresDefault A7200
Header append Cache-Control "proxy-revalidate"
</FilesMatch>

Related Posts

Previous post:

Next post: