Nginx/Password: Difference between revisions
From charlesreid1
| Line 12: | Line 12: | ||
Suppose you want to let people access the web server using the username <code>foo</code> and the password <code>bar</code>. | Suppose you want to let people access the web server using the username <code>foo</code> and the password <code>bar</code>. | ||
Set the username foo: | Set the username foo and the password bar using openssl: | ||
<pre> | <pre> | ||
sudo sh -c 'printf "<user>:$(openssl passwd -apr1 <your password>)\n" >> /etc/nginx/.htpasswd' | |||
</pre> | </pre> | ||
| Line 27: | Line 22: | ||
<pre> | <pre> | ||
cat /etc/nginx/.htpasswd | |||
</pre> | </pre> | ||
Revision as of 06:55, 8 March 2022
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:
sudo sh -c 'printf "<user>:$(openssl passwd -apr1 <your password>)\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 the 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_basicauth_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;
}
}