6

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?

Brad Werth
  • 17,411
  • 10
  • 63
  • 88
cfernandezlinux
  • 861
  • 1
  • 10
  • 23

3 Answers3

14

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
Community
  • 1
  • 1
Stefan Huska
  • 547
  • 1
  • 7
  • 13
4

I ended up doing something like this:

constraints :subdomain => "meow" do   
  match "/" => redirect { |params| "http://www.externalurl.com" }
end
Brad Werth
  • 17,411
  • 10
  • 63
  • 88
cfernandezlinux
  • 861
  • 1
  • 10
  • 23
1

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.

David
  • 652
  • 2
  • 12
  • 21