I've written an analogous question about Apache configuration, but I'm also interested in nginx.
Is it possible to require Basic Authentication for all except specified User Agents in nginx configuration?
I've written an analogous question about Apache configuration, but I'm also interested in nginx.
Is it possible to require Basic Authentication for all except specified User Agents in nginx configuration?
After several evenings of research and trial and error, I found that conditional authentication can be created combining map
directive with custom variable for auth_basic
directive:
map $http_user_agent $authentication {
default "Access Restricted";
"~^PayPal IPN" "off";
# ...
}
server {
# ...
location / {
auth_basic $authentication;
auth_basic_user_file /etc/nginx/.htpasswd;
# ...
}
}
Yes, it is possible by using nginx map
directive.
For example:
map $http_user_agent $auth {
default 0;
"~Chrome" 1;
}
server {
... other vhost config ...
if ($auth = 1) {
auth_basic "Authenticate";
auth_basic_user_file /path/to/authfile;
}
}
The map
directive looks into the variable specified in the first argument and declares values for the second variable based on information inside the map
block.
Then we use the $auth
variable to see if we want to have authentication or not.
You can read more on how to match different strings with map
in nginx map documentation page at http://nginx.org/en/docs/http/ngx_http_map_module.html