Rails routing to handle multiple domains on single application

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')

Leave a Comment