How can I enable HTTP Basic Auth for everything except for a certain file?
Here is my current server block configuration for the location:
locat
Only auth_basic off didn't work for me If we have to skip auth for ALL uri's under our url
location ^~ /some/location/to_skip/ {
auth_basic off;
try_files $uri $uri/ /index.html;
}
I am doing something similar using "map" instead of "if" to assign the auth_basic realm variable and htpasswd file:
map $http_host $siteenv {
default dev;
~^(?<subdomain>.+)\.dev dev;
~^(?<subdomain>.+)\.devprofile devprofile;
~^(?<subdomain>.+)\.devdebug devdebug;
~^(?<subdomain>.+)\.test test;
~^(?<subdomain>.+)\.demo demo;
~^(?<subdomain>.+)\.stage stage;
# Live
~^(?<subdomain>.+)\.live live;
~^.*\.(?P<subdomain>.+)\.[a-zA-Z]* live;
}
map $http_host $auth_type {
default "Restricted";
~^(?<subdomain>.+)\.dev "Development";
~^(?<subdomain>.+)\.devprofile "Development";
~^(?<subdomain>.+)\.devdebug "Development";
~^(?<subdomain>.+)\.test "Testing";
~^(?<subdomain>.+)\.stage "Stage";
~^(?<subdomain>.+)\.demo "Demo";
# Live
~^(?<subdomain>.+)\.live "off";
~^.*\.(?P<subdomain>.+)\.[a-zA-Z]* "off";
}
server {
.. etc ..
auth_basic $auth_type;
auth_basic_user_file /etc/nginx/conf.d/htpasswd-$siteenv;
}
I'm doing the following:
location = /hc.php {
auth_basic "off";
}
location / {
try_files $uri $uri/ =404;
}
location = /somefile.txt {}
comes first, so location / {}
can capture the remaining requestsauth_basic "off"
requires the quotes around it as far as I knowProbably this would work in different orders, and/or without the double quotes also, but why not try to do things as correct and complete as possible, if possible.
The most important modifiers are:
(none) No modifier at all means that the location is interpreted as a prefix. To determine a match, the location will now be matched against the beginning of the URI.
=: The equal sign can be used if the location needs to match the exact request URI. When this modifier is matched, the search stops right here.
~: Tilde means that this location will be interpreted as a case-sensitive RE match.
~*: Tilde followed by an asterisk modifier means that the location will be processed as a case-insensitive RE match.
^~: Assuming this block is the best non-RE match, a carat followed by a tilde modifier means that RE matching will not take place.
quoted from here: https://www.keycdn.com/support/nginx-location-directive
Try to use sign = , that helps you:
location = /README {
auth_basic off;
allow all; # Allow all to see content
}