Amazon CloudFront for a Rails application

December 10, 2012 Link to post  Permalink

If you want to provide the best experience to the users of your Rails application, you should serve all of your static content using a Content Delivery Network, or CDN. There are many CDN providers, but one of the easiest to sign up for and configure is Amazon’s CloudFront service.

Here’s how I configured my Rails blog to use CloudFront to serve all the static assets.

In the AWS Console

  • Select the CloudFront option
  • Click the Create Distribution button
  • Set these options
    • Download
    • Your current domain name (for my blog, this is blog.craz8.com)
    • Origin ID: assets.domain-name (e.g. assets.blog.craz8.com)
    • Select which Price Class you want to be in - I used the default
    • use the defaults for all others
  • Click the Create Distribution button at the bottom
  • From the Distributions list, copy the Domain Name for the distribution you just created. Mine is d1za39ny3bo0r4.cloudfront.net
  • Wait for your new distribution status to change to Deployed (up to 15 minutes)

Now you have to edit a configuration option in your Rails code. In the production.rb configuration file, make this change to use the host name you just created:

  config.asset_host = 'http://d1za39ny3bo0r4.cloudfront.net'

Then deploy your application and enjoy!