Using CDN with Rails assets

March 25, 2013 · Posted in Development 

Using CDN (Content Delivery Network) server to serve assets (images and other static files like css, js) on Rails is very easy with assets pipeline.

 

Change config in production.rb:

# serve all assets from CDN server
config.action_controller.asset_host = 'http://cdn.mydomain.com'
 
#or if your files in a folder on CDN server
config.action_controller.asset_host = 'http://cdn.mydomain.com/myfolder'
If you have an image at http://mydomain.com/assets/myimage.jpg then it will be replaced on your HTML  page with URL http://mydomain.com/myimage.jpg (or http://mydomain.com/myfolder/myimage.jpg for the second example).

To use CDN server only for images (but not for stylesheets or javascripts):

# serve only images
config.action_controller.asset_host = Proc.new { |source|
if source =~ /\b(.png|.jpg|.gif)\b/i
"http://cdn.mydomain.com"
end
}

Examples on github:

https://gist.github.com/maxivak/5239159

 

For more flexible settings you can use this gem: https://github.com/cmer/rails-assets-cdn

 

 

Comments

  • Jiří Kratochvíl

    Great! Very useful. Thank you.