How to Redirect WWW to non WWW (and vice versa)

Written by Kent
Updated over a week ago
Routing constraints make this really easy. Here's one for each option.

These will redirect all URLs and the root path too. They would need to be the first routes in your routes file to work.
  # Remove www with redirect
  constraints subdomain: 'www' do
    get ":any", to: redirect(subdomain: nil, path: "/%{any}"), any: /.*/
    root to: redirect(subdomain: nil, path: "/"), as: :www_root
  end

  # Add www with redirect
  constraints subdomain: false do
    get ":any", to: redirect(subdomain: "www", path: "/%{any}"), any: /.*/
    root to: redirect(subdomain: "www", path: "/"), as: :non_www_root
  end
You could also do this in Rack Middleware before it makes it to Rails as well.

Was this article helpful?