Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect from old domain to new one (SEO friendly)

I changed the custom domain on my Heroku app to a new one. Now I will create a new Heroku app which only purpose will be to redirect to the first app.

I read in Google Webmasters that I should do a 301 redirect like this:

http://old.com/anypath/123

to

http://new.com/anypath/123

How do I do it in Rails?

like image 686
Martin Petrov Avatar asked Sep 28 '11 05:09

Martin Petrov


People also ask

Does redirecting domains help SEO?

Redirects are not bad for SEO, but — as with so many things — only if you put them in place correctly. A bad implementation might cause all kinds of trouble, from loss of PageRank to loss of traffic. Redirecting pages is a must if you make any changes to your URLs.

Do you lose SEO if you change domain?

Yes, changing a domain name can impact SEO. The search engines have indexed the pages on your existing domain. The change throws the search engines for a loop. Moreover, your current domain has an established track record.


2 Answers

Put this in a before filter in the ApplicationControlller:

class ApplicationController
  before_action :redirect_if_old

  protected

  def redirect_if_old
    if request.host == 'old.com'
      redirect_to "#{request.protocol}new.com#{request.fullpath}", :status => :moved_permanently 
    end
  end
end
like image 92
Ben Lee Avatar answered Sep 23 '22 20:09

Ben Lee


In your controller action:

redirect_to "http://new.com#{request.request_uri}", :status => 301

However, Heroku has what may be a slightly better option for you documented in their dev center:

class ApplicationController
  before_filter :ensure_domain

  APP_DOMAIN = 'myapp.mydomain.com'

  def ensure_domain
    if request.env['HTTP_HOST'] != APP_DOMAIN
      # HTTP 301 is a "permanent" redirect
      redirect_to "http://#{APP_DOMAIN}#{request.request_uri}", :status => 301
    end
  end
end
like image 44
Andrew Marshall Avatar answered Sep 19 '22 20:09

Andrew Marshall