Nginx config: how to use auth_basic authentication if ssl_client_certificate none provided?

authentication, config, drupal, nginx

Solution

You can set `auth_basic` configuration in the `if` clause like this:

server {
    listen 443;
    auth_basic_user_file    .htpasswd;
    ssl_client_certificate  ca.cert;
    ssl_verify_client       optional;
    ...

    location / {
      ...

      if ($ssl_client_verify = SUCCESS) {
        set $auth_basic off;
      }
      if ($ssl_client_verify != SUCCESS) {
        set $auth_basic Restricted;
      }

      auth_basic $auth_basic;
    }
}

Now, authentication falls back to HTTP Basic if no client certificate has been provided (or if validation failed).

Problem

I'm trying to set up Nginx server as follows: First, the server should check whether the user provides the client SSL certificate (via ssl_client_certificate). If the SSL certificate is provided, then give access to the site, If the SSL certificate is NOT provided, then ask the user to enter a password and logs through auth_basic. I was able to configure both the authentication method at the same time. But this config is superfluous. To make check, whether the user provides its SSL certificate I try the config like this: ``` 18: if ($ssl_client_verify != SUCCESS) { 19: auth_basic "Please login"; 20: auth_basic_user_file .passfile; 21: } ``` But Nginx returns an error: "auth_basic" directive is not allowed here in .../ssl.conf:19 How can I to set the condition in this case?

Original source