Nginx – Require Basic Auth for Specific IPs

http-authenticationhttp-basic-authenticationnginx

I have a whitelist of IPs for nginx, but in addition to this I want to require basic authentication for specific IP.

For example, allow access for these IPs:

198.51.100.1
198.51.100.2

require basic authentication for this IP:

198.51.100.3

and deny for anyone else.

How is this possible? satisfy directive doesn't seem to solve this problem

Best Answer

You could implement this with the GEO directive: http://nginx.org/en/docs/http/ngx_http_geo_module.html#geo

Just a sketch using your ip address examples:

geo $authentication {
default "Authentication required";
198.51.100.1 "off";
198.51.100.2 "off";
198.51.100.3 "on";
...
}

server { ... location / { satisfy any;

# basic auth referencing to geo with $authentication auth_basic $authentication; auth_basic_user_file /etc/nginx/.htpasswd; # whitelist for the inital ip address restrictions include /etc/nginx/conf.d/ip-whitelist.conf.include; deny all; }}