'best method to require passwords for some pages in a web site
I have a site with most material publicly available but about 10% should be password protected. The site is published using NGINX on a Debian system.
What is the best approach to protect the few directories and single pages with a password (or some other form of authentication) ?
I think that NGINX would allow me to protect some directories, but this seems coarse and I am not sure if just ordering and listing all the directories to protect in the site configuration is a good idea.
I am obviously not an expert on NGINX configuration and thus my suspicion that there is a better way?
I have tried to use the advice given, but do not succeed. I have now:
map $uri $realm {
/Reserved "Username and Password required";
default off;
}
server {
server_name a.b.c;
root /var/www/html/homepage;
auth_basic $realm;
auth_basic_user_file /etc/nginx/.htpasswd;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
location /homepage {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}
access_log /var/log/nginx/heiden.log;
...
}
What must go into the map, when the URI is a.b.c/Reserved/index.html and all other files in Reserved/* should be protected? I have tried a.b.c/Reserved/* but it did not trigger the password request (or is the firefox saved passwords playing tricks with me?).
Solution 1:[1]
I don't see any way except the list of URI's you need to protect. Here is the example to protect them using the basic auth and the map block with the list of URIs to protect:
map $uri $realm {
/uri/to/protect/1 "Protected area";
/uri/to/protect/2 "Protected area";
...
default off;
}
server {
...
auth_basic $realm;
auth_basic_user_file /path/to/.htpasswd;
...
}
You can also use PRCE (or PCRE2 for nginx 1.21.5 or later) regex patterns inside the map block using the ~ (for case-sensitive matching) or ~* (for case-insensitive matching) string prefix if your list can be somehow simplified that way. For example, to protect every URI starting with /path/to/protected/area you can use the following map block:
map $uri $realm {
# every URI starting with the following prefix will require basic authorization
~^/path/to/protected/area "Protected area";
...
}
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 |
