Example: Expiration of Static Content with Apache

This may require you to edit your Apache configuration. There are three places where this can be done:

  • The global configuration file, httpd.conf, usually found in /etc/httpd/conf/httpd.conf;
  • A sub-configuration file, usually found in /etc/httpd/conf.d;
  • An htaccess file, usually in the directory where the content is located, if allowed by your server.

Consider a directory or a group of files to which you want to apply an expiry date, and hence an Expires header.

For a directory, insert a block in the configuration which matches that directory:

<Directory /home/user/html/foo>
...
</Directory>

For a group of files, by matching a regular expression pattern on the file name:

<FilesMatch .*\.jpg$>
...
</FilesMatch>

You can't use a block inside an htaccess file, but you can use FilesMatch.

Within this block, enable mod_expires and specify a default expiry date for all matching files[1][2]:

ExpiresActive On
ExpiresDefault modification "plus 5 hours"

This indicates that the content should expire 5 hours after the file's modification time. Any requests after that time will not be cached at all.

You can override the default for specific MIME types:

ExpiresByType text/html "now plus 1 hour"

This indicates that HTML documents will expire 1 hour after they are requested, regardless of the modification time of the file on disk, and all other content will use the default.


References

[#1] Apache 1.3 mod_expires documentation: http://httpd.apache.org/docs/1.3/mod/mod_expires.html

[#2] Apache 2.2 mod_expires documentation: http://httpd.apache.org/docs/2.2/mod/mod_expires.html