First, make sure all the virtual host site conf file has no default_server.

Then, make a new conf file under /etc/nginx/conf.d/. For me I use default.conf.

Add the following into this file to block all the direct IP access for port 80, or http.

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

where _ catches all the domain names pointing to your server’s IP address and the configuration will block all traffic to your IP address (http://YOUR_IP_ADDRESS) by returning the default 404 Not Found Nginx page.

To block direct access to IP for port 443 or https, use the following and add it to the same default.conf.

server {
 listen 443 ssl http2;
 listen [::]:443 ssl http2;
 server_name example.com;
 
 ssl_certificate /etc/nginx/ssl/example.com.crt;
 ssl_certificate_key /etc/nginx/ssl/example.com.key;

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

Then, I need to make a self-signed certificate for the fake domain exmaple.com. Run the one-line command below to make it.

sudo mkdir /etc/nginx/ssl/

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/example.com.key -out /etc/nginx/ssl/example.com.crt

After the above settings. Anyone who wants to access the server IP address in the browser address bar, no matter whether it is HTTP or HTTPS,  he will get a 404 Not Found error.

 

 

David Yin

David is a blogger, geek, and web developer — founder of FreeInOutBoard.com. If you like his post, you can say thank you here

Leave a Reply

Your email address will not be published. Required fields are marked *