Forum Moderators: phranque

Message Too Old, No Replies

Nginx IP to Domain Redirect

Is this Nginx redirect correct?

         

WebOpz

9:44 pm on Oct 8, 2021 (gmt 0)

5+ Year Member Top Contributors Of The Month



I've got a new server which redirects from all DNS requests to https to the domain name. The server already uses Let's Encrypt and redirects all domain.ext and www.domain.ext to the correct HTTPS location just fine.

I was having an issue with redirecting from the IP address and I added return 301 https://$host$request_uri; below.

Is return 301 https://$host$request_uri; correct to redirect from IP to the domain?
server { if ($host = www.example.ext) { return 301 https://$host$request_uri; }

server {
if ($host = www.example.ext) {
return 301 https://$host$request_uri;
}


if ($host = example.ext) {
return 301 https://$host$request_uri;
}


listen 80 default_server;
listen [::]:80 default_server;

server_name example.ext www.example.ext;
return 301 https://$host$request_uri;


Is that correct or am I missing something?

[edited by: phranque at 11:24 pm (utc) on Oct 8, 2021]
[edit reason] unlinked url [/edit]

phranque

11:51 pm on Oct 8, 2021 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



Is return 301 https://$host$request_uri; correct to redirect from IP to the domain?

what is the value of the Location: header in the response?



Is that correct or am I missing something?

it seems that by using $host you may end up with the IP address.
from the nginx doc:
in this order of precedence: host name from the request line, or host name from the “Host” request header field, or the server name matching a request

source: http://nginx.org/en/docs/http/ngx_http_core_module.html#var_host

robzilla

9:48 am on Oct 9, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



If you want to redirect all traffic for that server on port 80 to a single canonical domain, simply use:
server {

listen 80 default_server;
listen [::]:80 default_server;

server_name _;

location ~ {

return 301 https://www.example.com$request_uri;

}

}