Getting "Too many redirects" error with nginx rewrite rule
Solution 1:
Right now any and all requests are going to hit this server block:
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
server_name _; # This doesn't do anything
rewrite ^ $scheme://www.example.com$request_uri permanent;
# Rest of file irrelevant
}
Because: no server block has a valid server_name (therefore there will never be host name match) and this is the default_server.
Use appropriate server names
Therefore to always redirect requests hitting the server to a given hostname ensure that there is a server block explicitly for www.example.com
:
server {
listen 80;
listen [::]:80 ipv6only=on;
server_name www.example.com;
# Everything else from "Tomcat server block"
# or the proxy_pass config as appropriate
}
And redirect requests with any other host name to it:
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
return 301 http://www.example.com$request_uri;
# Nothing else, because it wouldn't do anything
}
In the above note that return 301
is used as it's considered a better practice than an unconditional rewrite rule.