DEV Community

Mikhail Salosin
Mikhail Salosin

Posted on

AWS CloudFront on Rails

Content Delivery Network is a useful tool to reduce the latency of delivering images, scripts, and stylesheets to your customer. Since we at Revealbot are using AWS as our cloud provider we decided to give Amazon's own CDN CloudFront a try.

In this post I'll describe how to setup Rails and CloudFront to work with each other.

On the Rails side configuration is pretty straightforward. To enable CDN we need to add one line to our production.rb config file:

config.asset_host = 'cdn.revealbot.com'
Enter fullscreen mode Exit fullscreen mode

Now we need to set up CloudFront. Go to CloudFront page in the AWS console. Click on Create distribution. Fill in the Origin domain, with the site domain select protocol that CloudFront will use to access your sites.

Image description

In the Settings tab enter the domain name that will be used as the CDN subdomain and request an SSL certificate to enable HTTPS.

Image description

Then click Create Distribution. It will take AWS a couple of minutes to roll up distribution to all regions, in the meantime, we can continue our setup. Click on created distribution and go to the Origins tab. Since we only want to serve our assets through CDN we can add additional "fake" origin invalid.invalid that will help us reject all requests except for assets.

Image description

Ok, almost done, now let's set up path rules, go to Behavior and create rules that will define how CDN is processing different paths. This is our current setup:

Image description

Notice that the Default (*) path is set to invalid.invalid that we set up earlier, this will prevent CDN from serving anything else besides assets - images, fonts, stylesheets, and js files.

And that's it, redeploy your production app and all assets will be served through CloudFront CDN.

Top comments (0)