how to disable direct access to a web site by ip address

Solution 1:

server {
    listen      80 default_server;
    listen      [::]:80 default_server;
    server_name "";
    return      444;
}

You need to specify default_server parameter so that all non available server requests goes to this server block which throws 444 error.

444 : CONNECTION CLOSED WITHOUT RESPONSE

ref: https://httpstatuses.com/444

Solution 2:

You can use redirect, nginx config:

server {
        listen 80;
        server_name IP_ADDRESS;
        return 301 http://YOUR.DOMAIN;
}

Solution 3:

You can just add a server directive before others.

server {
    listen 80;
    server_name _;
    return 404;
}