Nginx/Password
From charlesreid1
To password protect a folder on an Nginx server:
- Create an .htpaasswd file that contains the username and the hashed password
- instruct nginx to use the .htpasswd file to authenticate users trying to access a particular location
Create the Password File
OpenSSL
Here we use openssl to create the password file, which is a hidden file called .htpasswd in the /etc/nginx configuration directory.
Suppose you want to let people access the web server using the username foo and the password bar.
Set the username foo:
sudo sh -c "echo -n 'foo:' >> /etc/nginx/.htpasswd"
Now add the hashed password bar using openssl:
sudo sh -c "openssl passwd -apr1 >> /etc/nginx/.htpasswd"
You can repeat this process for additional usernames. You can see how the usernames and encrypted passwords are stored within the file by typing:
cat /etc/nginx/.htpasswd
Output
foo:$apr1$wI1/ER4B$kTOuTJHkTWkekoQnXqC1d1
Modify sites-available file
Here is the original nginx default sites-available:
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /usr/share/nginx/html;
index index.html index.htm;
server_name localhost;
location / {
try_files $uri $uri/ =404;
}
}
To modify this to use the .htpasswd file we created above, add the two directives:
auth_basicauth_basic_user_file
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /usr/share/nginx/html;
index index.html index.htm;
server_name localhost;
location / {
try_files $uri $uri/ =404;
auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;
}
}