Rails routes redirection for subdomains

2019-04-27 12:17发布

问题:

We can't change the server configuration files, so we need to do our redirections at the rails level.

I have no problem with path redirections to external sites, like:

match "/meow" => redirect("http://meow.com/")

The issue is with the subdomains. I need to redirect for example:

http://my.example.com => http://example.com

How can this be done using routes.rb?

回答1:

According to @cfernandezlinux's amazing answer, here's the same in Rails 4/Ruby 2 syntax:

constraints subdomain: "meow" do   
  get "/" => redirect { |params| "http://www.externalurl.com" }
end
  • match in routes.rb is not allowed in Rails 4.0 anymore. You have to use explicitly get, post, etc.
  • hashrocket syntax (=>) is for old Ruby, now in Ruby 2.0 we use param: 'value' syntax


回答2:

I ended up doing something like this:

constraints :subdomain => "meow" do   
  match "/" => redirect { |params| "http://www.externalurl.com" }
end


回答3:

I hope this railscast can help:

http://railscasts.com/episodes/221-subdomains-in-rails-3

http://railscasts.com/episodes/123-subdomains