Changing domain for Rails application

Often we have to change domain on which does our Rails application work. Usually it is no problem, since we can run application accessible under both URLs and wait for Google to index new URLs.

But it is not always as easy. For example Google Maps API key is bound to application URL, so with URL change we need change Google Maps API key too. And serve proper one depending on which URL was used. So more logical solution is to force all requests coming to old URL to be redirect with HTTP 301 to proper URL. It is also better since we won’t get penalty from Google for duplicated content, and when we turn off the old domain smaller part of traffic will be lost (HTTP 301 mean that search engine should change URL pointing to page, since it is Moved Permanently)

WWW home page
Image from SXC.hu

In most cases You can do it with redirect feature from webserver like NGiNX, Apache or whatever You do use. However it mean You has to use scary regexps and not always is easy to modify webserver config (very common in corporate environment ;)) )

In such case You has to built this into Rails application. You can do it with following code in app/controllers/application.rb:

 def redirect_domain
    uri = URI.parse request.url
    if uri.host != CONF[:main_host]
      uri.host = CONF[:main_host]
      headers["Status"] = "301 Moved Permanently"
      redirect_to uri.to_s
      return
    end
    return true
  end

and add before_filter :redirect_domain. Of course You have to define CONF[:main_host] as proper hostname for Your service (without any http:// or trailing slashes, just domainname.com). You should be aware, that it does not affect any static HTML file, since they are served by webserver, without calling Rails (this includes pages cached via page caching).

This is very simple solution and does not deal with situation if Your application uses some sub domains.

Does anybody know other solution for easy domain change on live application?

Join the Conversation

4 Comments

  1. @Sebastian
    Well… it depends on what You except.

    If You have user1.APPLICATION.com and user2.APPLICATION.com this code won’t be OK -> it will redirect all request to APPLICATION.com (assuming this is value of CONF[:main_host]).

    In such case You has to use some regexp substitution. Something like this (written from head, not tested):

    if uri.host =~ /OLD_DOMAIN^/
      uri.host.gsub!(/OLD_DOMAIN^/, NEW_DOMAIN)
    
  2. NetManiac: very clever solution!
    Your filter should return false explicitly after redirect (ARAIR simple “return” doesn’t interrupt filter chain).

    Sebastian:
    You could also use .split(“.”) on uri.host and check how many parts it has and replace some of them.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.