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

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