Prevent unwanted domains from forwarding to Nginx.

The other day, I noticed that a number of spammy domains were redirecting to one of my Nginx web servers. I only noticed this because my logs showed that Googlebot was crawling my site with an incorrect host name.

Limit Nginx to specific hostname.

To prevent unwanted domains from forwarding to your Nginx server, you can to use a “catch all” server block. This server block will catch any request that does not contain a valid hostname.

#Example /etc/nginx/sites-available/default configuration.

#Our catch all server block, which returns a 403 header.
    listen 80 default_server;
    listen [::]:80 default_server;
    return 403;

#The server block for our website.
    listen 80;
    listen [::]:80;
    #Specify the valid hostnames for this server block.
    #The rest of your configuration.

Please note that you should backup your configuration files and test any changes BEFORE restarting Nginx. Don’t blame me if the configuration above does not suit your setup. You may need to tweak it a little.

A quick drill down of the Nginx configuration above:

  • We created an extra server block at the top of our configuration file.
  • Our first server block is the default server. It will catch any requests coming in on port 80. Notice how I used the “default_server” parameter in this block.
  • Our second server block is also listening on port 80. However, it will only serve requests for, or I achieved this by removing theĀ “default_server” parameter that was originally in this block.

If a request comes in and the hostname is, then the first server server block will catch it and return a 403 Forbidden error. You can change this to a 404 if you think that is more apt.

Hopefully, you found this guide to be helpful.

See also: Forcing HTTPS with Nginx.