nginx: Do not require Basic Authentication only if http request is OPTIONS

Vincent Gagnon picture Vincent Gagnon · Jun 16, 2017 · Viewed 9.6k times · Source

The Authorization Header is not sent with an HTTP OPTIONS Request. I would like disable this authentication only when the request is OPTIONS and leave it on for other requests. Here is the relevant piece of config code I have at the moment. cannot seem to see why it does not work. I always get a 401 Unauthorized Error on OPTIONS request.

    location ~ /foo/bar
    {

      if ($request_method = OPTIONS) {
        set $auth_basic "off";
      }
      if ($request_method != OPTIONS)
      {
        set $auth_basic "Resctricted";
        set $auth_basic_user_file /var/www/.htpasswd;
      }
      auth_basic $auth_basic;
      auth_basic_user_file $auth_basic_user_file;
    }

Answer

Poyoman picture Poyoman · Feb 9, 2018

It looks like it is an old post, but found this solution :

Put the following configuration inside "location" and remove any auth_basic from server. This will work

  location / {
    # Your node proxy configuration for example #

    # Make options requests work #
    limit_except OPTIONS {
      auth_basic "Restricted access zone";
      auth_basic_user_file /etc/nginx/pass/protected;
    }
  }