views:

51

answers:

2

I have about 10 domains pointing to my Heroku app (it took forever to settle on a name for the site -- don't ask), all of which I've given to various people at various times.

Now that I've decided on a domain name (call it "example.com"), I want the existing domains to all work, but to redirect to example.com. What's the best way to do this?

Here's my approach (in application_controller.rb):

before_filter :ensure_domain

def ensure_domain
  canonical_domain = 'example.com'

  if request.env['HTTP_HOST'] != domain && ENV["RAILS_ENV"] == 'production'
    redirect_to request.protocol + canonical_domain + request.env["REQUEST_URI"]
  end
end

Is this the right approach?

+3  A: 

Actually I'd do it in Apache:

<VirtualHost ...>
  ServerName example.com
  .... # your real server config
</VirtualHost>

<VirtualHost ...>
  ServerName olddomain.com
  ServerAlias other-olddomain.com yetanotherone.com
  Redirect permanent / http://example.com/
</VirtualHost>

Note that the trailing slash on the redirect url is important. no it will redirect anything coming to http://olddomain.com/foo/bar?foo=bar to http://example.com/foo/bar?foo=bar

Vitaly Kushner
A: 

I think keeping the logic in my Rails application is easier to manage (plus I don't know how to configure Apache). I ended up going with this:

before_filter :ensure_domain

def ensure_domain
  canonical_domain = 'example.com'

  if request.host != canonical_domain && ENV["RAILS_ENV"] == 'production'
    redirect_to request.protocol + canonical_domain + request.request_uri
  end
end
Horace Loeb