Apache htaccess: Add Cache-Control header per file type

Written by
Date: 2012-12-29 10:38:32 00:00

This tip is specially useful if you are serving a static file using Apache.

I know a lot of you may say, why not use Nginx? And that is a valid question, but sometimes you may need .htacces file for other sites beside your static site right? In those cases Apache is your option.

In the past I used to install Nginx in front of Apache just to serve static sites with Nginx, and make Nginx send back to Apache PHP requests. After learning about Apache MPM worker I now prefer to install just Apache with external PHP

Well, too much introduction, let's go to the tip.

Insert Cache-Control header with .htaccess file on a per file type basis

Edit your .htaccess file and insert something like this:

 # 1 Month for all your static assets
 <filesMatch ".(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
 Header set Cache-Control "max-age=2592000, public"
 # 1 DAYS for rss feeds and robots
 <filesMatch ".(xml|txt)$">
 Header set Cache-Control "max-age=86400, public, must-revalidate"
 # 4 HOURS for your real articles files
 <filesMatch ".(html|htm)$">
 Header set Cache-Control "max-age=14400, must-revalidate"

I use something like this for my Jekyll powered static site.