简体   繁体   中英

How can I route a subdomain to rails app in routes.rb?

I have a url https://www.openhub.net which is my rails 4.2.7 app. I have a separate subdomain on another system which is https://code.openhub.net/ . If you clink on the second link, this will reroute you to a discontinued page. What's hosting the code.openhub.net url is going to be decomissioned and will be rerouted to openhub.net . So what I'm trying to do is that when someone tries to go to code.openhub.net my rails app that has the openhub.net will serve a static page. The problem is that I can't conceptualize how this will work. For example, here is a snippet of rails documentation under routing.

3.9 Request-Based Constraints You can also constrain a route based on any method on the Request object that returns a String.

You specify a request-based constraint the same way that you specify a segment constraint:

get 'photos', to: 'photos#index', constraints: { subdomain: 'admin' }

You can also specify constraints in a block form:

namespace :admin do
  constraints subdomain: 'admin' do
    resources :photos
  end
end

Request constraints work by calling a method on the Request object with the same name as the hash key and then compare the return value with the hash value. Therefore, constraint values should match the corresponding Request object method return type. For example: constraints: { subdomain: 'api' } will match an api subdomain as expected, however using a symbol constraints: { subdomain: :api } will not, because request.subdomain returns 'api' as a String.

I understand what the document is saying but when I try to put this code into practice, I'm stumped. Here is my routing.rb file:

get '???', to: '???', constraints: { subdomain: 'code' }

I understand that the subdomain constraint portion of the url will be code but will the get and to be? How do I know will go under get? Do I simply substitute get code.openhub.net which will route to a CodeController#index ? Has anyone tried to do something like this before? From the documentation I see that the request object has an original_url method that I can call. Is there perhaps a way I can make use of this? Any help would be greatly appreciated.

  • As a sidenote, I noticed that subdomain is not a property of the request object outlined here Rails Request Object

This should work:

get '/', to: 'code#index', constraints: { subdomain: 'code' }

That will route requests to https://code.openhub.net/ to the the index method in your CodeController .

However, the URL will still say https://code.openhub.net/ . If you don't want that, you might try a redirect, like this:

get '/', to: redirect('https://www.openhub.net/'), constraints: { subdomain: 'code' }

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