Basic auth only if a certain header is present in the request?

Solution 1:

According to the documentation of the auth_basic directive, you can not use the directive in a if block but you can use variables as values.

So use a map to test for specific conditions and use the resulting variable.

map $http_<header_name> $authentication {
    default    "off";
    "~^"       "my_realm";
}


server {

     ...    

    location /foo {

        auth_basic $authentication;
        auth_basic_user_file /path/to/htpasswd/file;

        ...
    }

}

The <header_name> pattern must be replaced with the name of the header using lowercase letters and underscore instead of dashes (e.g. My-Header becomes $http_my_header)