Restricting multiple directories to same IP ranges
Suppose I have the following in an nginx configuration file:
location ^~ /foo/ {
allow 1.2.3.4;
allow 5.6.7.8;
allow 9.10.11.12;
…
allow 99.100.101.102;
deny all;
# rest of directives
}
If I also want to restrict access to several other directories, is it possible to do so without having to create another block and list the IPs all over again? My concern is making changes when IPs are added and removed in the future — I would not want to have to make sure that each block was updated.
Even better would be a directive that basically allows me to "include" the list of IPs under each block somehow.
Solution 1:
As soon as I typed the word "include" in my question above, the wheels started spinning in my head.
Turns out you can absolutely just put allow
and deny
directives into an include file and they will work just as expected. Best of all, this means I can combine lists of IPs so certain groups of servers can access some directories while others can't.
I have it set up like so:
/etc/nginx/includes/admin-ips
allow 1.2.3.4/32;
allow 1.2.3.5/32;
/etc/nginx/includes/private-ips
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
/etc/nginx/includes/testing-ips
allow 4.5.6.7;
allow 8.9.10.11;
/etc/nginx/conf.d/server.conf
location ^~ /admin/ {
include includes/admin-ips;
deny all;
# rest of directives
}
location ^~ /tools/ {
include includes/admin-ips;
include includes/testing-ips;
include includes/private-ips;
deny all;
# rest of directives
}
location ^~ /tests/ {
include includes/admin-ips;
include includes/testing-ips;
deny all;
# rest of directives
}
Works like a charm.