Efficient way of blocking / denying nginx connections via IP

Viewed 46

I would like to filter several different endpoints by IP using nginx. My current solution is to cut and paste the following code for each endpoint:

    location /api0 {
        allow 123.45.67.89; 
        allow 98.765.43.21; 
        deny all;
        ......
    }

    location /api1 {
        allow 123.45.67.89; 
        allow 98.765.43.21; 
        deny all;
        ......
    }

    etc

Is there a more efficient way of setting up these IP filters? Is it possible to setup a group so I can use that for all the endpoints in the config file?

My main issue here is that sometimes an IP address needs to be changed, which means I have to manually cut & paste the IP and then restart nginx.

Thanks!

1 Answers

You can put those directives in the server block and they will apply to all locations in the server block.

Or, if you don't want the rules in all locations, you can put these lines

allow 123.45.67.89; 
allow 98.765.43.21; 
deny all;

into a separate file, say /etc/nginx/allowlist, and then include the file where necessary:

    location /api0 {
        include allowlist;
        ......
    }

    location /api1 {
        include allowlist;
        ......
    }
Related