Nginx basic auth - exception by location doesn't work

September 16, 2019 154 views
Security Ubuntu 16.04 Nginx

Hello,

we’ve got an Ubuntu 16.04 and a Nginx server with several virtlual hosts, like

We added a basic auth on each of the hosts using this tutorial.

The auth itself works fine, but then we tried to add exceptions to it for pages like that:
https://one.test-host.org*/inner-api/service/…*

So such URLs woudn’t require basic auth.
It’s worth of note that this is a logical path - no such folders exist on the server.

Many of the answers online went like this:

location /inner-api/service/ {
    auth_basic off;
}

Or, via map Nginx directive:

map $uri                   $use_basic_auth {
    ~/inner-api/service/   off;
    default                "Restricted";
}

# some other configs...

auth_basic $use_basic_auth;

But this is where things got strange.

  1. At first, adding this code to the host Nginx config resulted in 404 error on any of the URLs to match.

  2. Then, couple of days later, this behavior changed. Now Nginx just doesn’t match the /inner-api/service pattern at all - it gives basic auth on all URLs.
    We didn’t do anything with the configs in this couple of days.

What may be the reason for this, and how can we make basic auth exceptions work?

1 Answer

Hello,

I think that you are headed in the correct direction. You just need to make sure that you have the additional rules in your /inner-api/service/ location.

For example, let’s say that you have a server bock with the following basic auth for your / location:

location / {
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/passwd;
    proxy_set_header Host $host;
    proxy_pass http://socket_nodes;
}

Then you would need the same rules in your /inner-api/service so that Nginx would know how to handle the requests:

location /inner-api/service {
    auth_basic "off";
    proxy_set_header Host $host;
    proxy_pass http://socket_nodes;
}

So rather than having only the auth_basic "off"; line, you need to make sure that you have the rest of the configurations there as well.

Hope that this helps.
Regards,
Bobby

Have another answer? Share your knowledge.