Posted over 10 years ago. Visible to the public.

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.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Thomas Eisenbarth
Last edit:
about 8 years ago
Attachments:
.htaccess
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Thomas Eisenbarth to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more