Telling browser to cache JS/CSS and images

Most modern browsers should cache static content, like images, CSS and JS to make page load faster. But if you feel like being polite administrator – you can instruct your server to tell that in the headers, so browsers do that even more politely. 😉

Anyway – this tiny bit of config is good to have. Consists of 2 parts – disabling ETAG and setting expiring period for specific files.

ETAG technology is used by browsers to achieve similar effect – it sends sort of checksum of a file (inode, modification time, etc) and if this checksum changes – browser will redownload the file. As I read on the internet (and that makes sense!) – if you use traffic compression (and you should do that!) – then under specific conditions this ETAG might not work well.

Here are configuration for apache 2.4:

# REMOVE ETAG
Header unset ETag
FileETag None

# set expire date (+1 day to try) for JPG, PNG, GIF, JS and CSS
<IfModule mod_expires.c>
  <FilesMatch "\.(jpe?g|png|gif|js|css)$">
    ExpiresActive On
    ExpiresDefault "access plus 1 day"
  </FilesMatch>
</IfModule>

After webserver restart – check file response headers. You should see a line

“Cache-Control: max-age=…….”

If you see it – then everything is good. If not – check list of “LoadModule” if you are loading “mod_expires” module. 😉