Skip to content

Instantly share code, notes, and snippets.

@maxivak
Last active April 28, 2021 12:17
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save maxivak/6727458 to your computer and use it in GitHub Desktop.
Save maxivak/6727458 to your computer and use it in GitHub Desktop.
Redirect from WWW to a non-WWW version of site in Rails.details:http://maxivak.com/redirect-from-www-to-a-non-www-version-of-site-in-rails/
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
# in apache virtual host configuration file
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com
RewriteRule ^ http://example.com%{REQUEST_URI} [L,R=301]
# in nginx server configuration file
server {
listen 80;
server_name www.example.com;
return 301 http://example.com$request_uri;
}
server {
listen 80;
server_name example.com;
...
}
@gus4no
Copy link

gus4no commented Oct 29, 2015

using match without the via option would fail, you should add this via: [:get, :post] after the redirect block ends to make it work.

@gus4no
Copy link

gus4no commented Oct 29, 2015

constraints(host: /^www\./i) do match '(*any)' => redirect { |params, request| URI.parse(request.url).tap { |uri| uri.host.sub!(/^www\./i, '') }.to_s }, via: [:get, :post] end

@odanylevskyi
Copy link

odanylevskyi commented Apr 28, 2021

This should work for all methods

constraints(host: /^www\./i) do
    match '(*any)', via: :all, to: redirect { |_, request|
      # parse the current request url & tap in and remove www.
      URI.parse(request.url).tap { |uri| uri.host.sub!(/^www\./i, '') }.to_s
    }
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment