Nginx restrict domains

The first server defined in Nginx is treated as the default_server so by just adding one as the default and returning 412 (Precondition Failed) or any another status that best fits your requirements, will help for the subsequent servers to obey the server_name

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    return 412;
} 

server {
    listen   80;
    server_name mysite.lk www.mysite.lk;
    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass "http://127.0.0.1:8080";
   }
}

All of the above answers are correct. But they all don't work if the other domain tries to access your host via port 443(https/SSL).

To Block access to https requests just add an if block in the https server configuration of your host.

server {

    server_name www.xyz.com xyz.com;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }


    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot

    if ($host = "www.specificdomainyouwanttoblock.com") {
        return 404;
    }

    if ($host = "specificdomainyouwanttoblock.com") {
        return 404;
    }

    # or you can simply add:

    if ($host != "yourdomain.com") {
        return 404;
    }

}

Tags:

Nginx