Make Browsers Cache Static Files With mod_expires On Apache2 (Debian Squeeze)
Author: Falko Timme
Follow me on Twitter
Last edited 03/07/2011
I do not issue any guarantee that this will work for you!
1 Preliminary Note
I'm assuming you have a working Apache setup on your Debian Squeeze server, e.g. as shown in this tutorial: Installing Apache2 With PHP5 And MySQL Support On Debian Squeeze (LAMP)
2 Enabling mod_expires
mod_expires can be enabled as follows:
Restart Apache afterwards:
3 Configuring mod_expires
The mod_expires configuration can be placed in the overall Apache server configuration, inside a virtual host container, inside a <Directory> directive, or inside an .htaccess file.
In this example, I will place it in Apache's default vhost which is configured in /etc/apache2/sites-available/default on Debian Squeeze:
If you have multiple file types that should expire after the same time after they have been accessed (let's say in one week), you can use a combination of the FilesMatch and the ExpiresDefault directives, e.g. as follows:
[...] <IfModule mod_expires.c> <FilesMatch "\.(jpe?g|png|gif|js|css)$"> ExpiresActive On ExpiresDefault "access plus 1 week" </FilesMatch> </IfModule> [...]
This would tell browsers to cache .jpg, .jpeg, .png, .gif, .js, and .css files for one week.
Restart Apache after your changes:
Instead of using FilesMatch and ExpiresDefault directives, you could also use the ExpiresByType directice and set an Expires header (plus the max-age directive of the Cache-Control HTTP header) individually for each file type, e.g. as follows:
You can use the following time units in your configuration:
Please note that Apache accepts these time units in both singular and plural, so you can use day and days, week and weeks, etc.
It is possible to combine multiple time units, e.g. as follows:
ExpiresByType text/html "access plus 1 month 15 days 2 hours"
Instead of basing the Expires header on the access time of the browser (e.g. ExpiresByType image/jpg "access plus 60 days"), you can also base it on the modification date of a file (please note that this works only for real files that are stored on the hard drive!) by using the modification keyword instead of access:
ExpiresByType image/gif "modification plus 7 days"
To test if your configuration works, you can install the Live HTTP Headers plugin for Firefox and access a static file through Firefox (e.g. an image). In the Live HTTP Headers output, you should now see an Expires header and a Cache-Control header with a max-age directive (max-age contains a value in seconds, for example 604800 is one week in the future):
- Apache2 mod_expires: http://httpd.apache.org/docs/2.0/mod/mod_expires.html
- Live HTTP Headers Plugin for Firefox: https://addons.mozilla.org/en-us/firefox/addon/live-http-headers/
- Debian: http://www.debian.org/