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 and the password bar using openssl, using /etc/nginx/.htpasswd
as the destination:
sudo sh -c 'printf "<user>:$(openssl passwd -apr1 <your password>)\n" >> /etc/nginx/.htpasswd'
NOTE: leave out the password to be interactively prompted for it (more secure):
sudo sh -c 'printf "<user>:$(openssl passwd -apr1)\n" >> /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 an example original nginx default sites-available:
/etc/nginx/sites-available/default
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_basic
auth_basic_user_file
/etc/nginx/sites-available/default
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; } }