Nginx location regex match everything but home

nginxregex

I am trying to restrict access to everything but home "/".

I mean: allow people to access example.com but restrict access with password to any other path: example.com/any-other-path.

I have tried multiple combinations of regex with the location directive, but haven't make it work:

location ~ /\.+ {
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

location ~ /.+ {
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

location ~ /. {
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

And some other but either I restrict access to all (example.com and example.com/*) or don't restrict access to anything.

Could someone point me in the right direction, already read this and this and searched in this forum but I am having trouble with this implementation.

Best Answer

You need to match files without directories in their path and allow access, and subsequently match everything else and require authentication. For example

location ~ ^/[^/]*$ {<no auth directives>}
location ~ ^/.+/.*$ {<some auth directives>}