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

By Lowell Heddings on May 2nd, 2017

nginxoptions

While setting up this site, 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 that would have also allowed me to more easily use my mobile devices to access the site. 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.howtogeekpro.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.