How to Block Other Domain Access to Your Nginx Web Server

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.


  • An Nginx web server installed and running.

  • Must be logged in with SSH and basic Linux commands

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 "";

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/

server {
    # Only allow access if the host is correct
    # Block other domain access
    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


Did you find this article valuable?

Support Nishant Kumar by becoming a sponsor. Any amount is appreciated!