Setting Apache expires header

by Tweak on June 8, 2009
in Apache

There’s two ways of getting there with Apache. mod_expires yields the most flexible solution, but mod_headers will work too, if you cannot use mod_expires for some reason.

mod_expires

  • First, enable the mod_expires module :
    For Apache to send along Expires with your staticly served files, you will need to make sure that mod_expires has been installed on your server. It is fairly standard and none of my servers I checked (that includes OS X’s Apache installation), didn’t have mod_expired on the system. You may have to search through your httpd.conf file and uncomment (remove the pound-signs) from the following lines, however:

    #LoadModule expires_module libexec/httpd/mod_expires.so
    #AddModule mod_expires.c

  • Once you’ve uncommented these lines, you should restart Apache.
    Service httpd restart

  • Now you can use mod_expires. There are several ways to configure a future expires header (as per the documentation), I’ll use ExpiresDefault inside a FilesMatch directive:


    ExpiresActive On
    ExpiresDefault "access plus 1 month"

    This configuration will cause all graphics, PDFs, CSS, JavaScript and flash movies to be sent out with an expires header one month from the date they were requested. This means clients always receive a date into the future, and instead use their cached copies instead.

    If you’d like more fine grained control, you can use the ExpiresByType directive.

    The FilesMatch directive matches files based on a regular expression and can be tweaked to your liking. For instance, if you’d like these settings only to apply to your design assets (and not content images) you could do this instead:


    ExpiresActive On
    ExpiresDefault "access plus 1 month"

    The FilesMatch directive can go in your VirtualHost configuration.

mod_headers

  • If you cannot use mod_expires for some reason, you can achieve a similar effect using mod_headers. This module allows you to set arbitrary headers. Using this we can manually set an Expires header as such:


    Header set Expires "Thu, 15 Apr 2010 20:00:00 GMT"

    This needs occasional updating. Update: As Samuli points out in the comments, you should not set an expires header more than one year into the future (according to the HTTP 1.1 RFC). This means you’ll need to tend to this solution atleast once a year, should you choose to do things this way.

Share and Enjoy:
  • email
  • Print
  • PDF
  • Facebook
  • Digg
  • del.icio.us
  • Google Bookmarks
  • StumbleUpon
  • MySpace
  • Live
  • Twitter
  • Yahoo! Buzz

Comments are closed.