3

I've written an analogous question about Apache configuration, but I'm also interested in nginx.

Is it possible to require Basic Authentication for all except specified User Agents in nginx configuration?

2 Answers 2

7

After several evenings of research and trial and error, I found that conditional authentication can be created combining map directive with custom variable for auth_basic directive:

map $http_user_agent $authentication {
    default "Access Restricted";
    "~^PayPal IPN" "off";
    # ...
}

server {
    # ...
    location / {
        auth_basic $authentication;
        auth_basic_user_file /etc/nginx/.htpasswd;
        # ...
    }
}
1

Yes, it is possible by using nginx map directive.

For example:

map $http_user_agent $auth {
    default 0;
    "~Chrome" 1;
}

server {
    ... other vhost config ...
    if ($auth = 1) {
        auth_basic "Authenticate";
        auth_basic_user_file /path/to/authfile;
    }
}

The map directive looks into the variable specified in the first argument and declares values for the second variable based on information inside the map block.

Then we use the $auth variable to see if we want to have authentication or not.

You can read more on how to match different strings with map in nginx map documentation page at http://nginx.org/en/docs/http/ngx_http_map_module.html

1
  • Unfortunately, auth_basic directive doesn't work inside of an if condition. Syntax error is raised. But the working solution is very similar. Aug 27, 2017 at 18:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .