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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)