Redirecting www URL requests to non-www URL (and vice-versa) in Rails 3

It is probably not a good idea to have your website reachable from both “www.” URL as well as “non-www” top-level URL. As this diverts traffic (and bookmarks) to two different URIs while also possibly splitting up search-engine’s page-ranking. While “www.” URLs have their own advantages (e.g., familiarity, cookie-less sibling subdomain), non-www URLs take at least one less DNS query to resolve and are shorter.

Here is how to achieve the redirection in Rails 3:

  # config/routes.rb
  constraints(:host => "www.example.net") do
    # Won't match root path without brackets around "*x". (using Rails 3.0.3)
    match "(*x)" => redirect { |params, request|
      URI.parse(request.url).tap { |x| x.host = "example.net" }.to_s
    }
  end

And the reverse i.e., redirecting “without-www” to “www”:

  # config/routes.rb
  constraints(:host => "example.net") do
    match "(*x)" => redirect { |params, request|
      URI.parse(request.url).tap { |x| x.host = "www.example.net" }.to_s
    }
  end  


4 responses to "Blog | Redirecting www URL requests to non-www URL (and vice-versa) in Rails 3"

  1. http://inst.myopenid.com/ says at February 16, 2012 at 5:04 PM

    Does it works on last versions of Rails?

    Could it be modified to be domain agnostic?

  2. Not Entered says at October 10, 2012 at 4:22 PM

    Hi,
    It works on the last 3.x version of rails.

    Also it can be domain agnostic. Here is domain agnostic version for this:

    1
    2
    3
    4
    5
    6
    
      # config/routes.rb
      constraints(subdomain: '') do
        match "(*x)" => redirect do |params, request|
          URI.parse(request.url).tap { |x| x.host = "www.#{x.host}" }.to_s
        end
      end
    

  3. Not Entered says at October 10, 2012 at 4:24 PM

    oops: little mistake

    here it is:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    Hi,
    It works on the last 3.x version of rails.
    
    Also it can be domain agnostic. Here is domain agnostic version for this:
    
    1
    2
    3
    4
    5
    6
      # config/routes.rb
      constraints(subdomain: '') do
        match "(*x)" => redirect { |params, request|
          URI.parse(request.url).tap { |x| x.host = "www.#{x.host}" }.to_s
        }
      end
    

  4. Not Entered says at October 10, 2012 at 4:25 PM

    Hate when I can't edit my posts :) :)



Post a comment


(lesstile enabled - surround code blocks with ---)

Featured posts

Subscribe to this blog

Blog topics