Setting Up Amazon CloudFront With Rails

S

Recently I introduced CloudFront to my side-project Candl (a book tracking app). In this article I’d like to share why would you need it and how to implement it in a Rails project (spoiler: very easy!)

What Is Amazon CloudFront?

Amazon CloudFront is a CDN (content delivery network) which means it can deliver your content (images, JS scripts and CSS stylesheets, also anything else really) in a most efficient way.

Say if your customer accesses your site from Japan, a CDN usually will have a copy of your resource cached somewhere geographically close to your user, and will serve it from there. User benefits because he will get the resource very fast. Your server benefits as well as it doesn’t have to serve the resource, it is served by the CDN.

Setting Up

Go to your AWS console, then to CloudFront, then create a new distribution. It is fine to let most of the settings by default as they are very sane.

Make sure to put your original domain name (www.candlapp.com in my case).

If your site is served via HTTPS, as it should nowadays, set the “Origin Protocol Policy” to “HTTPS only”.

Also, I highly recommend setting Compress Objects Automatically (scroll to the very bottom to find it) to “Yes” so that JS and CSS files will be served in a compressed form (I really don’t understand why this isn’t on by default).

After the distribution is created you will get a special address which looks like youruniquecode.cloudfront.net. This is the CDN we now want our assets to serve from.

Setting Up Rails To Use The CDN

In order to prepare our Rails app we only need to add one thing. Open config/environments/production.rb and insert a new line.

Now Rails knows about your new CDN. That’s pretty much it. You can deploy your application now and make sure that assets are being served from the new CDN host.

Solving The Font CORS Problem

One issue you may encounter is that modern browser won’t allow your website to load fonts from 3rd party domain names (in this case cloudfront.net). In order to solve it, the server should explicitely say that those resources are allowed to be served to your hostname. If you want to know more, please read this brilliant article on CORS from Mozilla.

But for our purpose we just need to add several headers when we serve fonts. There are multiple ways to do this. I did it by setting up nginx which I have in front of my app.

In this snippet, we basically say, that any font file is allowed to be loaded from one specific origin which is https://www.candlapp.com with one specific method (GET).

Please make sure, when dealing with CORS settings to only allow as minimum as possible.

Now you know how easy it is to setup a CDN in a typical Rails application.

Where To Go From Here

Recent Posts

Categories

Meta