NGINX redirecting the wrong subdomains

httpsnginxweb-server

I have setup my NGINX to only accept HTTPS traffic on port 443 and I want to redirect all non-HTTPS traffic from port 80 to HTTPS.

I also have multiple subdomains I want to manage independently.

I'm going to post an example from my configuration but will omit the boring stuff.

The main website that regular user should be able to browse:

server
{
    listen 443 ssl;
    listen [::]:443 ssl;

    server_name www.myserver.com;

    root /var/www/www.myserver.com;

    index index.php index.html index.htm;
}

One of the subdomains:

server
{
    listen 443 ssl;
    listen [::]:443 ssl;

    server_name subdomain.myserver.com;

    location /
    {
        proxy_pass https://127.0.0.1:8500;
    }
}

And now I want to redirect traffic from port 80 to HTTPS:

server
{
    listen 80;
    listen [::]:80;

    server_name subdomain.myserver.com;

    return 301 https://subdomain.myserver.com$request_uri;
}

The Problem: ALL subdomains are automatically being redirected to "https://subdomain.myserver.com", even if they do not match the server name specified in the redirect block.

"http://www.myserver.com" (for which there is no config block) will get redirected to "https://subdomain.myserver.com" even though it doesn't match the server_name

Best Answer

Add a "Catch All" server block, as documented:

server {
    listen 80 default_server;
    server_name _;
    server_name_in_redirect off;
    location / {
        return 404;
    }
}

Another possible cause for the "redirects" are HSTS heades. Once a client has seen HSTS headers with includeSubDomains set on the main domain, it will also try to access it's subdomains directly with HTTPS, without trying HTTP first.