Is there any way to allow a group of ip in the certain range to access my website?(Nginx)

Suppose, I want to allow access to my project for the IP falling between 192.168.1.1 and 192.168.1.40.

Nginx example:

  stream {
        #...
        server {
            listen 12345;
            deny   192.168.1.2;
            allow  192.168.1.1/24;
            allow  2001:0db8::/32;
            deny   all;
        }
    }

I have to allow each and every IP separately or is there any technique that will allow access to the ip falling in the given range?


The allow and deny statements are evaluated in order, until a match is found, so you could impose a strict range of 192.168.1.1 to 192.168.1.40 inclusive, with five consecutive statements.

For example:

deny  192.168.1.0;
allow 192.168.1.0/27;
allow 192.168.1.32/29;
allow 192.168.1.40;
deny  all;

192.168.1.0/27 represents 192.168.1.0 to 192.168.1.31 inclusive, with the first address explicitly denied by the previous statement.

192.168.1.32/29 represents 192.168.1.32 to 192.168.1.39 inclusive.


For the range 192.168.1.130 to 192.168.1.190, start by looking at the binary representation of the last byte:

130 = 10000010
190 = 10111110

So this can be represented by allowing 10xxxxxx but first denying 1000000x and 10111111.

For example:

deny  192.168.1.128/31;
deny  192.168.1.191;
allow 192.168.1.128/26;
deny  all;