Disable Direct IP Access in Nginx (HTTP & HTTPS) .

If you use nginx for shared hosting and thus work with server blocks (virtual hosts) it is best to block access to the web server through the server ip address both with “http” and “https”. With the solution we propose here we also prevent that domains that have an A record and thus point to the server but for which no server block has been created yet are also rejected. This also prevents a random SSL certificate from being used for virtual host for which no https was set up in the server block.

Move the nginx “default.conf” file to save as back-up.

# mv /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf.orig

Create a new “default.conf” file.

# vi /etc/nginx/conf.d/default.conf

Add following code:

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

    ssl_reject_handshake on;

    server_name _;

    return 444;

Check the configuration.

# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

And restart nginx.

# systemctl restart nginx

Similar Posts