Apache: Setting Expire and Cache-Control Headers for Image Files

Posted on in System Administration

One of the suggestions for improving the performance of your website is to properly set the Expire and Cache-Control headers of the HTTP response for images. Since images rarely change, the Expire time should be set far in the future. This ensures that web browsers will attempt to retrieve the image from their local cache rather than requesting it from your web server. If you do need to change an image, simply changing the image's URL will ensure the browser pulls the new image rather than something from the cache.


Similarly, it is also advisable for web browsers to retrieve cached images from proxy servers when available. This again saves your web server from answering an additional request. Since proxy servers are designed to respond quickly, it is likely that the remotely cached images are retrieved faster than your server can manage.

Here are the changes you need to make in your Apache HTTP server configuration to set a long expire time and enable public caching:

LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so

<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType image/gif  "access plus 1 year"
  ExpiresByType image/jpeg "access plus 1 year"
  ExpiresByType image/png  "access plus 1 year"

<IfModule mod_headers.c>
  <FilesMatch "\.(gif|jpe?g|png)$">
    Header set Cache-Control "public"

As you can see, I've set the expire time for GIFs, JPEGs, and PNGs to be a year after they are accessed by the web browser. This might be a bit excessive, but once I create an image and place it on the site, I never replace it with an image of the same name.

Slaptijack's Koding Kraken