CloudFront CDN as Rails asset host

We wrote about this topic pretty extensively a few years ago, but the landscape has changed somewhat, and it’s now easier than ever to set up a CloudFront CDN to serve the assets from your Rails app.

Using a CDN for your assets is a best practice because it improves load times for your visitors and reduces the effort required from your Rails servers.

Step 1: Configure Rails to send the correct response headers on requests for fonts

This is really easy, thanks to the font_assets gem. (Ignore what it says about Rails 3.1. It’s still good, even in Rails 5.) Simple add to your Gemfile:

gem 'font_assets'

We’ve chosen to put it in the :production group, as we don’t use an asset host in test or development mode.

If you’re OK allowing any site to load your fonts, you’re done with this step. If you want to lock it down more, see the Usage section of the README.

Step 2: Set up a CloudFront distribution

  1. Log in to AWS.
  2. Navigate to CloudFront.
  3. Click “Create Distribution”.
  4. Set the Origin Domain Name and your preferences for HTTP/HTTPS.
  5. Here’s the tricky bit! You’ll need to allow the HTTP OPTIONS method and forward the Origin HTTP Header. Here’s how it looks when you’ve got it right:

Once the distribution is “Deployed”, you should be all ready to move on to the final step!

AWS has more extensive documentation on this topic, but I had a hard time finding it at first.

Step 3: Configure Rails to use your new CloudFront distribution as its asset_host

In config/environments/production.rb or in config/initializers/assets.rb (the latter seems fashionable these days), add:

if ENV['ASSET_HOST'].present?
  config.action_controller.asset_host = ENV['ASSET_HOST']

Then set the ASSET_HOST env var in your environment(s), deploy your new code, and you should be all set!