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

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:

[codesyntax lang=”bash”]
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
[/codesyntax]

Redirect using Rails 3 routes

file config/routes.rb:

[codesyntax lang=”bash”]
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
[/codesyntax]

 

 

 

Redirect using nginx

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

[codesyntax lang=”bash”]
server {
listen 80;
server_name www.example.com;
return 301 http://example.com$request_uri;
}

server {
listen 80;
server_name example.com;

}
[/codesyntax]

 

Redirect using Apache

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

 

 

References:

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>