When serving multiple sites from one VPS using Nginx is common the need to disable access to a site using the server's IP. Luckily there is a really easy way to accomplish this. You just need to create a new site that responds to the IP and responds with a 404. For this example I'm assuming you're running Ubuntu as your server's OS. This might work on another linux OS but don't take my word for it.

To create a site just go to your Nginx's installation /sites-available directory. This directory is commonly located at /etc/nginx/sites-available, run in your terminal:

cd /etc/nginx/sites-available  

Once in the directory create a new server config file or edit one of the server files that you have there. For this example let's create a new one and add the server block there, I'll use nano to edit the file, run in your terminal:

touch empty_site  
nano empty_site  

Add this server block, make sure to replace <server_ip> with your server's IP.

server {  
    listen      80;
    listen      443; # add this to block HTTPS access
    server_name <server_ip>;
    return      404;
}

Save and exit the file.

Now we just have to enabled the site and restart the Nginx server. To enable the site lets navigate to the /sites-enabled directory inside the Nginx config and create a symlink for the server config file that we previously created, run in your terminal:

cd /etc/nginx/sites-enabled  
ln -s /etc/nginx/sites-available/empty_site empty_site  

Once this is done, we just have to restart the nginx server and everything should be working as expected, to restart run this:

sudo service nginx restart  

After that command completes go to your browser and try to access your site via the IP and it should show you an ugly 404 page :D. (If it doesn't work try with incognito mode in your browser, it might happen that your browser has the IP to site redirection in the cache)

Happy coding! :)


Comments? Something wrong in the post? or just want to contact me? Send me a tweet to @gpopoteur on twitter.