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. R
emember 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' end
301 redirect all non-www to www using rack rewrite
r301 /.*/, Proc.new {|path, rack_env| "http://www.#{rack_env['SERVER_NAME']}#{path}" }, :if => Proc.new {|rack_env| ! (rack_env['SERVER_NAME'] =~ /www\./i)}
Resources:
For further info please visit: https://github.com/jtrupiano/rack-rewrite/blob/master/README.rdoc