How to Block Access to Nginx Except for a Specific IP Address

While setting up a new website, I wanted to work on articles and tweaking things before actually launching to the public, so I needed a simple way to keep everybody else out until it was all ready to go. So I used the nginx access control feature to accomplish it.

It would have been more secure to setup nginx HTTP Auth instead and prompt for a username and password, and since it wouldn’t be tied to an IP address, it would have also allowed me to use my mobile devices to access the site even while out of the office. But if you’ve ever used HTTP auth you know that it’s extremely annoying, especially on mobile, to have to enter your credentials all the time.

So instead, I used a simple IP address allow rule for my office IP, and blocked everything else.

Open up your nginx.conf file (or whichever nginx configuration file you are using for your particular site) and add the following to either your server block or a specific location block, depending on how granular you want to get with the block.

To allow a range of IPs:

allow   10.1.1.0/24;

Or to allow only a single IP:

allow   10.1.1.2;

And then below that, to block everybody else:

deny all;

So you’ll end up with a server or location block that looks something like this:

server {
  listen  80;
  server_name www.testserver.com;

  allow 10.1.1.2;
  deny all;

It’s really about as simple as that. Now you’ll want to reload your nginx server, which you can do with this command for Ubuntu or Debian servers:

service nginx reload

Or you can directly reload using the nginx executable, assuming it’s located in the same place as mine (adjust the path otherwise)

/usr/local/nginx/sbin/nginx -s reload

The -s argument tells nginx you are going to send a “signal” and that signal is “reload”, which gracefully reloads the server without causing lots of problems.

It’s worth noting that simple IP restrictions are very useful, but aren’t a substitute for real security. If you really need to keep things secure, you’re better off setting up a VPN for access rather than using IPs that could be spoofed or unencrypted communications that can be spied on.

Lowell Heddings, better known online as the How-To Geek, spends all his free time bringing you fresh geekery on a daily basis. You can follow him on if you'd like.

  • Published 03/13/17
More Articles You Might Like