Rails routing to handle multiple domains on single application
Solution 1:
It's actually simpler in Rails 3, as per http://guides.rubyonrails.org/routing.html#advanced-constraints:
1) define a custom constraint class in lib/domain_constraint.rb
:
class DomainConstraint
def initialize(domain)
@domains = [domain].flatten
end
def matches?(request)
@domains.include? request.domain
end
end
2) use the class in your routes with the new block syntax
constraints DomainConstraint.new('mydomain.com') do
root :to => 'mydomain#index'
end
root :to => 'main#index'
or the old-fashioned option syntax
root :to => 'mydomain#index', :constraints => DomainConstraint.new('mydomain.com')
Solution 2:
In Rails 5, you can simply do this in your routes:
constraints subdomain: 'blogs' do
match '/' => 'blogs#show'
end