'Nginx: Skip HTTP Basic Authentication based on IP or request header
The http
block in nginx.conf
contains the following:
auth_basic $development_exceptions;
In an included file the geo
module is used to set the variable:
geo $development_exceptions {
default "Not allowed.";
1.2.3.4 "off";
}
The map
module uses the user agent variable in the same included file:
map $http_user_agent $development_exceptions {
default "Not allowed.";
~*(header-text) "off";
}
However, the setting of the development exceptions variable is competing, and so when the second code is applied the first code stops doing anything.
How can both strategies be combined? In this case it might not be possible to change nginx.conf
.
Solution 1:[1]
Then you should try below approach
geo $development_exceptions_geo {
default "Not allowed.";
1.2.3.4 "off";
}
map $http_user_agent $development_exceptions_agent {
default "Not allowed.";
~*(header-text) "off";
}
Now if you want to use or
condition then you can do below
map $development_exceptions_agent$development_exceptions_geo $development_exceptions {
~off "off";
default "Not allowed.";
}
If you want an and
condition then you can do below
map $development_exceptions_agent$development_exceptions_geo $development_exceptions {
~offoff "off";
default "Not allowed.";
}
Solution 2:[2]
I wanted to combine 'allowed IP-List' OR 'some User Agents' to bypass authentication, works:
geo $auth_geo {
default "Authentication required";
18.184.113.24 "off"; # pingdom
35.158.65.6 "off"; # pingdom
52.87.44.246 "off"; # url.thum.io
52.44.29.90 "off"; # url2.thum.io
}
map $http_user_agent $auth_agent {
default "Auth required";
"~PingdomPageSpeed" "off";
"~cutycapt" "off";
"~Chrome-Lighthouse" "off";
}
map $auth_geo$auth_agent $auth {
~off "off";
default "Not allowed.";
}
then use it similar to:
location ~ \.php$ {
auth_basic $auth;
auth_basic_user_file /etc/nginx/custom/website/htpasswd;
try_files $uri =404;
include fastcgi_params;
fastcgi_pass $phpupstream;
}
I do not know if auth_basic_user
can maybe also a relativ path (?).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tarun Lalwani |
Solution 2 |