Content Delivery Network (CDN) for Ruby on Rails with Nginx using AWS CloudFront

One of the significant way to enhance the performance is to implement a CDN to serve compiled assets in Rails.

The Problem:

Even though with the addition of asset pipeline has decreased the number of assets served and the file size, but sometimes the content is transmitted to the end user is slow. Distance also plays a role in the speed at which data can be delivered. Because of slow connection, users’   patience decreases and also your ability to effectively engage them.

Solution: Content Delivery network (CDN):

CDNs are networks of servers that host your content so that when you make a request, the request is served from a server closest to you. The use of CDN also reduces the number of requests hitting your application server (Apache/Nginx).

  • Nginx default site configuration for ruby on rails

CDN for Ruby on Rails with nginx using Cloudfront

CDN configuration:

In this configuration, the CDN will pull assets from your web server and cache it. All subsequent requests to that asset will be served straight from the CDN.

1. Login to AWS console and Click CloudFront

Login to Aws console and Click Cloudfront

 

2. Click Create Distribution

Click Create Distribution

 

3. Enter the domain where your assets currently live

Enter the domain where your assets currently live

 

4. Customize the Object Caching. Minimum TTL is set to one day

Customize the Object Caching. Minimum TTL is set to one day

 

5. Enter the Alternate Domain Name if any exists and rest be the defaults

Enter the Alternate Domain Name if any exists and rest be the defaults

6. Make note of CloudFront distribution URL

7. Enter the CloudFront distribution URL in Rails asset_host to changes the host url of assets.

# config/environments/production.rb

config.action_controller.asset_host = “XXXX.cloudfront.net”

Leave a Reply