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:
[codesyntax lang=”rails”]
# 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'
[/codesyntax]
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):
[codesyntax lang=”rails”]
# serve only images config.action_controller.asset_host = Proc.new { |source| if source =~ /\b(.png|.jpg|.gif)\b/i "http://cdn.mydomain.com" end }
[/codesyntax]
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
Jiří Kratochvíl says:
Great! Very useful. Thank you.