Redirect from WWW to a non-WWW version of site in Rails

September 27, 2013 · Posted in Development 

It is good practice to make your site available by both www.example.com and example.com URLs. But to prevent the duplication of pages (http://www.example.com/somepage/ and http://example.com/somepage are the same) we should have one version of URL (with WWW or without) and redirect from another version to the chosen one (from www to non-www or vice versa).

Examples:

www.example.com                  -> example.com
www.example.com/some/some-page -> example.com/some/some-page
www.example.com?some-query-param=value  -> example.com?some-query-param=value

Redirect using Rails 3 routes

file config/routes.rb:

Foo::Application.routes.draw do
  constraints(host: /^www\./i) do
    match '(*any)' => redirect { |params, request|
      URI.parse(request.url).tap { |uri| uri.host.sub!(/^www\./i, '') }.to_s
    }
  end
# other routes
end

 

 

 

Redirect using nginx

If your Rails app is hosted on nginx web server you can make redirect via config file for the server:

server {
    listen       80;
    server_name  www.example.com;
    return       301 http://example.com$request_uri;
}
server {
    listen       80;
    server_name  example.com;
    ...
}

 

Redirect using Apache

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com
RewriteRule ^ http://example.com%{REQUEST_URI} [L,R=301]

 

 

References:

all code is available here: https://gist.github.com/maxivak/6727458

Comments