301 redirect all non-www to www using rack rewrite

It took me quite a while to find a way to 301 redirect all my non-www urls to www urls. So I decided to create another quick reminder in case I need this code again in the future… But firstly, I needed to redirect pages that still existed but had permanently moved to another URL.

Here is the code using rack rewrite, for rails 3.x

First things first, include the  Rack Rewrite gem in your Gemfile:

gem 'rack-rewrite'

Then, load the middleware in the rails stack of our application. Put this code in an initializer (config/initializers/rack_rewrite.rb) since we will also include the redirection rules in this file. Remember to include your application namespace in the code snippet below:

YourApplicationName::Application.config.middleware.insert_before(Rack::Lock, Rack::Rewrite) do
  r301 '/pages/about-us', '/about-us'
  r301 '/pages/forms/contact-us', '/contact'
  r301 '/hello', '/welcome/hi'
The next step is to tell search engines that all my URLs without the www had permanently moved to the URLs with the www. It’s quite important for SEO purposes as the search engines won’t consider consider both sites have duplicate content. It’s also easier to check your Google Analytics (checking one set of results instead of 2)…

301 redirect all non-www to www using rack rewrite

r301 /.*/, {|path, rack_env| "http://www.#{rack_env['SERVER_NAME']}#{path}" },     :if => {|rack_env| ! (rack_env['SERVER_NAME'] =~ /www\./i)}



For further info please visit: 

IT Support Newcastle is brought to you by Transcendit Ltd, contact us on 0191 482 0444