How to redirect all your pages from www to root domain using ruby on rails

How to redirect all your pages from www to root domain using ruby on rails

July 30th, 2010 // 2:59 am @ Aymeric // 2 Comments

I realized today that my current configuration of taskarmy.com and www.taskarmy.com implied that Google considered them as two different domain names. This is bad for SEO for example (plus I had some login issues).

So I decided to redirect 301 all the pages coming from www to my root domain taskarmy.com.

(By the way, why are people still using www? I find this unnecessary.)

Anyway, this is the piece of code you can add in a before_filter method in your ApplicationController in a Ruby on Rails application:

    host = request.host.gsub(/www./,”)

    if /^www/.match(request.host)
      new_url = "#{request.protocol}#{host}#{request.request_uri}"
      redirect_to(new_url, :status => 301)
    end

 

Cheers,

Aymeric

Other articles you might like


Category : Programming tips and tricks

2 Comments → “How to redirect all your pages from www to root domain using ruby on rails”


  1. Sam G

    4 weeks ago

    There’s an even easier way to do this if your’e using nginx. You can remove the before filter and speed up your rails app.

    http://nginx.org/en/docs/http/converting_rewrite_rules.html

    Reply

  2. Aymeric

    4 weeks ago

    Thanks for the tip. Unfortunately, I am using Heroku which I don’t think will allow me change the rewrite rules.

    Reply

Leave a Reply

Subscribe now