Nginx basic auth - exception by location doesn't work


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:*/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?

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.


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