There was no information on the question what client was used to make the request. As written in nginx documentation, $host
variable contains:
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
Here, "request line" means the hostname after GET
verb in HTTP request.
Second one means the Host
header field.
Third one means the name configured in server_name
.
In your case, I think the test client did a request that did not contain Host
header. Therefore nginx used the server_name
configuration for the content of $host
variable.
Personally I just generate the HTTP -> HTTPS forward block for every virtual server, since I manage nginx configurations with Ansible. That way I can have a return 404
vhost for all other host names I am not interested in.
But if you need to implement a common vhost for the redirects, you can use following approach:
map $http_host $redirect_host {
~ (^.+$) $http_host;
default example.com;
}
server {
listen 80 default_server;
...
if ($scheme = http) {
return 301 https://$redirect_host$request_uri;
}
}
This always uses the HTTP host header for redirect target, except when there is no Host
header. In that case it uses example.com
for the redirect target. You can assign your main domain name as the redirect target for example.