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

If you use Nginx for shared hosting, it is recommended for security reasons to enforce strict compliance with SNI, where requests for domain names not hosted on the web server or the IP address of both “IPv4” and “IPv6,” from the server itself for both “HTTP” and “HTTPS” are rejected.

By default, Nginx chooses the first server block it can find if there is no matching “server_name” if the “default_server” is not configured, which is clearly not intended.

To prevent this, the “default.conf” file needs to be modified, closing all unwanted requests with Nginx’s non-default code 444.

As of Nginx version “1.19.4”, the newly added “ssl_reject_handshake” directive can be used to block direct IP access via “HTTPS” without the need for a valid SSL certificate.

This tutorial requires you to be logged in as root, so switch to root user if you are not already.

sudo -i

Move the current Nginx “default.conf” file to keep as a backup.

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

Create a new “default.conf” file.

cat > /etc/nginx/conf.d/default.conf << EOF
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;
}
EOF

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

Now, if you try to connect directly through the server IP address or a domain name that is not defined, the connection will be closed almost immediately, saving bandwidth and most importantly not exposing any hosted domain on the server.

Similar Posts