I am trying to rewrite the domain url that targets my site such that all domain names are rewritten to www.example.com and have the following config:
mysite block
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
server_name _;
rewrite ^ $scheme://www.example.com$request_uri permanent;
location / {
# Allow for large file uploads
client_max_body_size 0;
proxy_http_version 1.1;
proxy_pass http://mysite;
proxy_buffering off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
}
}
The tomcat server block
server {
listen 80;
root /opt/site2/www;
index index.html index.htm;
# Redirecto root requests to Share
rewrite ^/$ /share;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ /index.html;
}
# redirect server error pages to the static page /50x.html
error_page 502 503 504 /maintenance.html;
location = /maintenance.html {
root /opt/site2/www;
}
location /share {
# Allow for large file uploads
client_max_body_size 0;
# Proxy all the requests to Tomcat
proxy_http_version 1.1;
#proxy_buffering off;
proxy_pass http://backend;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $http_host;
proxy_set_header X-Forwarded-Server $host;
}
}
in the server block but I am getting a "too many redirects" error.
Right now any and all requests are going to hit this server block:
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
:And redirect requests with any other host name to it:
In the above note that
return 301
is used as it's considered a better practice than an unconditional rewrite rule.