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

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


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;    }  }


The simplest way to deal with this is allow nginx to handle the OPTIONS request:

server {    listen 80;    server_name  example.com;    root /var/www;    auth_basic "Resctricted";    auth_basic_user_file /var/www/.htpasswd;    location / {        if ($request_method = OPTIONS) {            add_header Access-Control-Allow-Origin "http://example.com";            add_header Access-Control-Allow-Methods "GET, OPTIONS";            add_header Access-Control-Allow-Headers "Authorization";            add_header Access-Control-Allow-Credentials "true";            add_header Content-Length 0;            add_header Content-Type text/plain;            return 200;        }    }}

This will allow OPTIONS to get a response without requiring authentication:

scott@Carl www $ curl -i -X OPTIONS http://example.comHTTP/1.1 200 OKServer: nginxDate: Sat, 17 Jun 2017 00:09:52 GMTContent-Type: application/octet-streamContent-Length: 0Connection: keep-aliveAccess-Control-Allow-Origin: http://example.comAccess-Control-Allow-Methods: GET, OPTIONSAccess-Control-Allow-Headers: AuthorizationAccess-Control-Allow-Credentials: trueContent-Length: 0Content-Type: text/plainscott@Carl www $ curl -i http://example.comHTTP/1.1 401 UnauthorizedServer: nginxDate: Sat, 17 Jun 2017 00:09:59 GMTContent-Type: text/htmlContent-Length: 188Connection: keep-aliveWWW-Authenticate: Basic realm="Resctricted"<html><head><title>401 Authorization Required</title></head><body bgcolor="white"><center><h1>401 Authorization Required</h1></center><hr><center>nginx</center></body></html>