Using CDN with Rails assets

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

 

 

One thought on “Using CDN with Rails assets”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>