Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving Assets on 'static' subdomain

How can I configure rails to serve assets on different subdomain? I basically want view/assets helpers to use subdomain for all static files, such as;

  • instead of example.com/application.css -> static.example.com/application.css
  • instead of example.com/application.js -> static.example.com/application.js
  • instead of example.com/logo.jpg -> static.example.com/logo.jpg
like image 659
Oguz Bilgic Avatar asked Jan 26 '12 11:01

Oguz Bilgic


2 Answers

do you know about the asset_host option?

# config/environments/production.rb
config.action_controller.asset_host = "static.example.com"

it's also possible to do dynamic names:

ActionController::Base.asset_host = Proc.new { |source|
  "http://assets#{Digest::MD5.hexdigest(source).to_i(16) % 2 + 1}.example.com"
}

http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html

like image 190
phoet Avatar answered Sep 19 '22 13:09

phoet


You can also try the rack-cors gem for Cross-Origin Resource Sharing. https://github.com/cyu/rack-cors

I've used this gem in a Rails 4 app when my font-awesome icons wouldn't render once I started using subdomains. This wiki put me on the right path: https://github.com/bokmann/font-awesome-rails/wiki/CORS-Cross-Domain-Support

Besides modifying my Gemfile, I also put the following code into config/application.rb toward the top according to this guide: https://github.com/cyu/rack-cors/blob/master/examples/rails4/config/application.rb

config.middleware.insert_before 0, "Rack::Cors", :debug => true, :logger => (-> { Rails.logger }) do
  allow do
    origins '*'

    resource '/cors',
      :headers => :any,
      :methods => [:post],
      :max_age => 0

    resource '*',
      :headers => :any,
      :methods => [:get, :post, :delete, :put, :patch, :options, :head],
      :max_age => 0
  end
end
like image 23
chemturion Avatar answered Sep 18 '22 13:09

chemturion