Search code examples
httpnginxdnssubdomain

Nginx drop when server_name does not match


I have two vhosts : one on domain.tld port 80, the other on sub.domain.tld port 443 with SSL on. I added a CNAME entry on my DNS server that redirects my sub subdomain to domain.tld.. Everything works as expected, but going to http://sub.domain.tld does the same as going to http://domain.tld, and https://domain.tld the same as https://sub.domain.tld. How can I prevent this ?

My configuration :

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

    server_name www.sub.domain.tld;

    ssl on;
    ssl_certifiate ...;
    ssl_certifiate_key ...;

    root /var/www/sub.domain.tld;
    ...
}

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

    server_name www.domain.tld;

    root /var/www/domain.tld;
    ...
}

Solution

  • If these are your only server blocks, then they are also your defacto default server blocks for port 443 and port 80 respectively. See [this document][http://nginx.org/en/docs/http/server_names.html] for details.

    If you do not want this, you need to declare a default server block. A minimalist definition might be:

    server {
        listen 80 default_server;
        listen 443 ssl default_server;
    
        ssl_certifiate ...;
        ssl_certifiate_key ...;
    
        return 403;
    }
    

    The ssl certificate is required to start the Nginx service, but it can be any certificate. Also, the ssl_certifiate directives are inherited, so you can place the default statements in the http block instead.

    Use return 444; to just close the connection with no response.