Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails routes redirection for subdomains

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?

like image 408
cfernandezlinux Avatar asked Dec 05 '12 01:12

cfernandezlinux


3 Answers

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
like image 152
Stefan Huska Avatar answered Nov 09 '22 13:11

Stefan Huska


I ended up doing something like this:

constraints :subdomain => "meow" do   
  match "/" => redirect { |params| "http://www.externalurl.com" }
end
like image 4
cfernandezlinux Avatar answered Nov 09 '22 12:11

cfernandezlinux


If you don't want to hard-code the URL (so, for example, you can test/use this locally), you could do:

  constraints subdomain: 'subdomain_from' do
    get '/' => redirect(subdomain: :new_subdomain, path: '')
  end

So now subdomain_from.google.com will redirect to new_subdomain.google.com.

like image 1
David Avatar answered Nov 09 '22 13:11

David