Allow only local users in nginx

Solution 1:

The listen directive tells the operating system on what interface the web server binds itself. So, when you look at netstat -a after starting nginx, you will see that nginx listens only on 127.0.0.1 IP port 80, which means that the nginx server cannot be reached via any other interface.

Binding to a specific IP address works in a lower level in the actual network stack than the allow / deny directives inside nginx configuration.

This means that you don't need separate allow / deny directives inside your configuration with your use case, because the connections are limited lower in the network stack.

If you specify listen 80; only, and use allow / deny directives, then nginx will send a HTTP error code to the client, tellng that access is denied.

With the listen 127.0.0.1; case, the browser cannot connect to the server at all, because there is no TCP port open for the browser to connect to.

Solution 2:

Let's say your network ID is 192.168.1.0, edit your conf file like so:

location / {
  # block one workstation
  deny    192.168.1.1;
  # allow anyone in 192.168.1.0/24
  allow   192.168.1.0/24;
  # drop rest of the world
  deny    all;
}

Please let me know how it works for you.

Edit #1:

Yes, the allow directive is a must according to the Official Nginx wiki. Their example is:

location / {
    allow 192.168.1.1/24;
    allow 127.0.0.1;
    deny 192.168.1.2;
    deny all;
}

Solution 3:

I wanted to achieve the same functionality (allow only local users in nginx) and I figured out that I can do something simple like this:

server {
    listen 127.0.0.1:80;

    index index.html index.htm index.nginx-debian.html;

    location = /favicon.ico { access_log off; log_not_found off; }

    location /static/ {
        root /path/to/folder;
    }       

    location / {
        include proxy_params;
    }
}

This config file works fine for me, I am not using any allow directive, but only 127.0.0.1:80, and with that I am able to restrict nginx access to local users only!