Read more

Putting static content on Cloudfront

Tobias Kraze
May 11, 2011Software engineer at makandra GmbH

We recently decided to put static content for HouseTrip.com Show archive.org snapshot to Amazon Cloudfront for a faster user experience. This happens fully automatically on deploy and is transparent in development. Together with a heavy use of sprites this sped up page load time quite nicely.

Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

These are a couple of the problems you need to solve in order to do this:

  • There is no good way to invalidate Cloudfront cached assets, and Cloudfront will ignore the usual ?123456 timestamps that Rails uses by default. So to make sure Cloudfront will not server outdated assets, you have to incorporate a timestamp or something similar into the actual filename. This needs to be done in your stylesheets, too, so they have to be dynamically rewritten before upload.
  • Cloudfront does not support on-the-fly gzipping. You can however upload an already gzipped version of your asset and set the Content-Encoding = gzip HTTP header. You then need to link to this gzipped asset only if the requesting browser actually supports it.
  • Upload web fonts you intent to use via @font-face is currently not possible, since Firefox will not use them unless they have a specific "cross-domain" HTTP header set that Cloudfront does not currently support.
  • Make sure you set a far-future expiration data, otherwise Cloudfront will invalidate its cache once a day.
  • Make sure assets are uploaded before anyone requests them (so do it early in your deploy recipe). If an non-existent asset is requested from Cloudfront, it will not recheck for its existence for 15 minutes.
  • Do not mix protocols. On an https page, you have to include your stylesheet over SSL, and all absolute paths within that stylesheet need to use SSL as well. Otherwise browsers will complain with a "mixed content" warning which is especially nasty on IE and Chrome.

We made use of menno's excellent cloudfront_asset_host gem Show archive.org snapshot , which already solves a lot of the issues, but had to make some changes (like proper SSL support), which can be found in our cloudfront_asset_host fork Show archive.org snapshot .

Posted by Tobias Kraze to makandra dev (2011-05-11 18:01)