How to set up AWS Cloudfront to serve Assets for Rails App

Agustin Vilaseca
Jan 26, 2016 · 2 min read

If you are wondering “why use a CDN to serve assets in the first place?”, then this article is not for you. However, if you have already decided you want to use cloudfront, then I hope you will find this helpful.

There are a lot of good write ups out there already on how to go about doing this. One good example is from Happy Bear Software.

However there are a few additional gotcha’s that you might run into. I’ll attempt to summarize all the necessary steps here.

Getting your rails App to serve assets

Next, if your app will be also serving fonts make sure to provide CORS support. An easy way to do this is to use rack/cors middleware making sure that it is before Rack::Static on your middleware stack.

e.g. first thing on your config.ru

require 'rack/cors'
use Rack::Cors do
allow do
origins '*'
resource '/assets/*', :headers => :any, :methods => [:get]
end
end

Create a AWS cloudfront distribution

And for CORS, make sure to whitelist the origin header, like so:

Image for post
Image for post

After your distribution is done provisioning, test that things are working by loadinghttps://your.cloudfront.net/assets/application-fingerprinted.css (look at your manifesto or some file from public/assets). Check that headers are correctly set for origin and max-age, etc. Hint: use your fav tool here e.g. Dev Console in Chrome

Have your App point to the new cloudfront distribution

config.action_controller.asset_host = "https://#{ENV['YOUR_CLOUDFRONT_CDN_DOMAIN']}"

and do the same for action mailer.

You dont have to use an Env variable here, but I found it useful that you can change domains without having to deploy new code.

Another tip is that you might want to add the https://your.cloudfront.net link to a dns prefetch on your page head to speed up page loads.

Engineering

From the builders of @EdSurge

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store