简体   繁体   中英

Ruby on Rails route for wildcard subdomains to a controller/action

I dynamically create URLs of the form username.users.example.com :

bob.users.example.com
tim.users.example.com
scott.users.example.com

All of *.users.example.com requests should go to a particular controller/action. How do I specify this in routes.rb ?

All other requests to www.example.com go to the normal list of routes in my routes.rb file.

UPDATE : I watch the railscast about subdomains and it showed the following bit of code which would seem to be exactly what I need (changed the controller and subdomain):

match '', to: 'my_controller#show', constraints: {subdomain: /.+\.users/}

The problem is it only matches the root URL. I need this to match EVERY possible URL with a *.users subdomain. So obviously I would put it at the top of my routes.rb file. But how do I specify a catch-all route? Is it simply '*' ? Or '/*' ?

I think, you just need to do the following :

create a class Subdomain in lib :

  class Subdomain  
    def self.matches?(request)  
      request.subdomain.present? && request.host.include?('.users')
    end  
  end

and in your routes :

constraints Subdomain do
  match '', to: 'my_controller#show'
end

You can constraint route dynamically based on some specific criteria by creating a matches? method

Lets say we have to filter sub domain of URL

constraints Subdomain do
  get '*path', to: 'users#show'
end

class Subdomain
  def self.matches?(request)
    (request.subdomain.present? && request.subdomain.start_with?('.users')
  end
end

What we are doing here is checking for URL if it start with sub domain users then only hit users#show action. Your class must have mathes? method either class method or instance method. If you want to make it a instance method then do

constraints Subdomain.new do
  get '*path', to: 'proxy#index'
end

you can achieve same thing using lambda as well like below.

Instead of writing class we can also use lambdas

get '*path', to: 'users#show', constraints: lambda{|request|request.env['SERVER_NAME'].match('.users')}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM