[ACCEPTED]-Rails routing to handle multiple domains on single application-subdomain

Accepted answer
Score: 98

It's actually simpler in Rails 3, as per 4 http://guides.rubyonrails.org/routing.html#advanced-constraints:

1) define a custom constraint class in 3 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 2 new block syntax

constraints DomainConstraint.new('mydomain.com') do
  root :to => 'mydomain#index'
end

root :to => 'main#index'

or the old-fashioned option 1 syntax

root :to => 'mydomain#index', :constraints => DomainConstraint.new('mydomain.com')
Score: 9

In Rails 5, you can simply do this in your 1 routes:

constraints subdomain: 'blogs' do
  match '/' => 'blogs#show'
end

More Related questions