Last active
April 28, 2021 12:17
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# in apache virtual host configuration file | |
RewriteEngine On | |
RewriteCond %{HTTP_HOST} ^www.example.com | |
RewriteRule ^ http://example.com%{REQUEST_URI} [L,R=301] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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; | |
... | |
} |
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
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
using
match
without thevia
option would fail, you should add thisvia: [:get, :post]
after the redirect block ends to make it work.