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

I realized today that my current configuration of and 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

(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 =,”)

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