Setting expiry dates for images, JavaScript and CSS

When deploying Rails applications you might have noticed that JS and CSS are not cached by all browsers.

In order to force Apache to add expiry dates to its response, add the attached .htaccess to the public directory. This will add a header such as Expires: Thu, 07 Oct 2010 07:21:45 GMT to the httpd response.

Configuring Apache

Check that you have mod_expires enabled. You need it for the attached .htaccess to work:

sudo a2enmod expires

Configuring Nginx

You can add this:

if ($request_uri  ~* "\.(gif|swf|flv|png|jp?g|js|ico|css)\?[0-9]+$") {
  expires max;
  break;
}

to your nginx configuration at the location context to add an expire header to all files matching the regex.

What about when I change a file?

Changed stylesheets and javascripts will always be reloaded because Rails appends a screen.css?1234567 timestamp to the paths. Background images referred to from the CSS won't have that timestamp however, so you will either need to change the filename or be OK with cached assets expiring after one day.

But doesn't my browser already send conditional requests?

Although your Browser might add correct conditional headers to the request of such files, Apache seems to ignore them.

Thomas Eisenbarth Over 13 years ago