Protecting a location by IP while applying basic auth everywhere else

Solution 1:

As you've found, it isn't advisable to but the auth settings at the server level because they will apply to all locations. While it is possible to turn basic auth off there doesn't appear to be a way to clear an existing IP whitelist.

A better solution would be to add the authentication to the / location so that it isn't inherited by /hello.

The problem comes if you have other locations that require the basic auth and IP whitelisting in which case it might be worth considering moving the auth components to an include file or nesting them under /.

server {
    listen 80 default;

    # Lock down the "root" directory to specific IP addresses
    location / {
        satisfy any;

        # Basic auth
        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/.htpasswd;

        # IP whitelist
        include /etc/nginx/conf.d/ip-whitelist.conf.include;
        deny all;

        # Inherits auth settings from parent
        location ~ \.php$ {
            # PHP specific config
        }
    }

    # Lock down the "hello" directory to specific IP addresses
    location /hello/ {
        # Developers only - ever!
        allow 12.34.56.78;
        deny all;
    }
    # ...
}