Archive for the Category 'apache'

How To Enable Client Side Cache For Static Images (in Apache)

Friday, September 22nd, 2006

I just read an interesting post (found on dzone) on client-side image caching, but unfortunately it was an ASP.NET solution for IIS. I wondered if there was an equivalent for Apache, and I was not let down.

It turns out it’s even easier in Apache since there’s already a module (mod_expires) for exactly this purpose. I configured the module and grabbed the headers for a random image on my site using the HEAD request code from this post and you can see from the before

Date: Fri, 22 Sep 2006 00:55:38 GMT
Server: Apache/2.2.3 (Unix) DAV/2 mod_jk/1.2.18 PHP/5.1.6
Last-Modified: Sat, 15 Jul 2006 16:25:02 GMT
ETag: "e5c1e3-6058-3d2cf380"
Accept-Ranges: bytes
Content-Length: 24664
Content-Type: image/png

and after

Date: Fri, 22 Sep 2006 01:32:03 GMT
Server: Apache/2.2.3 (Unix) DAV/2 mod_jk/1.2.18 PHP/5.1.6
Last-Modified: Sat, 15 Jul 2006 16:25:02 GMT
ETag: "e5c1e3-6058-3d2cf380"
Accept-Ranges: bytes
Content-Length: 24664
Cache-Control: max-age=2592000
Expires: Sun, 22 Oct 2006 01:32:03 GMT
Content-Type: image/png

that two headers were added:

Cache-Control: max-age=2592000
Expires: Sun, 22 Oct 2006 01:32:03 GMT

All I had to add to httpd.conf was

LoadModule expires_module modules/mod_expires.so
ExpiresActive On
ExpiresByType image/png A2592000

to cache png images for a month. While I was at it (since it works by mime type) I added caching for jpegs, gifs, and even JavaScript, CSS, and plain text (1 day for text files since they’re more likely to change), plus a global 5-minute default:

LoadModule expires_module modules/mod_expires.so
ExpiresDefault A300
ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/png A2592000
ExpiresByType text/css A86400
ExpiresByType text/plain A86400
ExpiresByType application/x-javascript A86400

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 License.