Read more

Setting expiry dates for images, JavaScript and CSS

Thomas Eisenbarth
September 07, 2010Software engineer at makandra GmbH

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

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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.

Posted by Thomas Eisenbarth to makandra dev (2010-09-07 09:14)