By default, Nginx doesn't block unwanted access to your web server when it's done directly to your server's IP address. This means that anyone can potentially access your server's resources. Here is how you can fix this issue.
Prerequisites
Open the Nginx Configuration File
Open your Nginx configuration file using a text editor. Typically, the file is located at /etc/nginx/sites-available/
You can use the command, nano filename to edit the file.
Modify the Configuration
Step 1: Your default_server should close all connections
Modify your Nginx default.conf /etc/nginx/sites-available/default.conf,
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name "";
return 444;
}
This change closes the connection whenever Nginx receives a request without a domain name.
Step 2: Your virtual host should check the server name and close unwanted connections
Modify your virtual host file, /etc/nginx/sites-available/example.com
server {
...
if ($host !~* ^(example\.com|www\.example\.com)$) {
return 403;
}
...
}
This simply disconnects the connection if the request was made to an unexpected domain.
Reload nginx and test the results
Test the Nginx configuration for any syntax errors:
sudo nginx -t
If the configuration test is successful, restart Nginx:
sudo service nginx restart
Done.