How to Set an Expires Header in Apache
Posted on Wednesday, 3rd February 2010 in Development by Simon
Setting an Expires (or Cache-Control) header in Apache will help speed up your website. I’m running Apache 2.x, and define an expires header for all of the site’s static assets (images, stylesheets, and scripts).
In Apache, mod_expires is a module that allows you to set a given period of time to live for web pages and other objects served from web pages. The idea is to inform web browsers how often they should reload objects from the server. This will save you bandwidth and server load, because clients who follow the header will reload objects less frequently.
The expires module is not compiled by default and must be enabled in the Apache httpd.conf file. Make sure the following is present and uncommented (remove preceding the #):
LoadModule expires_module modules/mod_expires.so
To set an expires header, simply add the following to the <virtualHost> section of your Apache vhost configuration:
ExpiresActive On ExpiresByType image/gif "access plus 1 months" ExpiresByType image/jpg "access plus 1 months" ExpiresByType image/jpeg "access plus 1 months" ExpiresByType image/png "access plus 1 months" ExpiresByType image/vnd.microsoft.icon "access plus 1 months" ExpiresByType image/x-icon "access plus 1 months" ExpiresByType image/ico "access plus 1 months" ExpiresByType application/javascript “now plus 1 months” ExpiresByType application/x-javascript “now plus 1 months” ExpiresByType text/javascript “now plus 1 months” ExpiresByType text/css “now plus 1 months” ExpiresDefault "access plus 1 days"
Alternatively you can add it to your htaccess file in an <ifModule mod_expires.c></ifModule> block.
If you need to change the length of time a type expires, simply change access plus 1 months to the appropriate length of time, e.g. access plus 1 days, access plus 365 days etc. The time length is by default specified in seconds, but you may also use any of these keys: years, months, weeks, days, hours, minutes and seconds.
You can read all about expires headers by reading Yahoo!’s Best Practices for Speeding Up Your Web Site guide.
Alternatively, read the Apache mod_expires documentation.