Basic HTTP Authentication With Nginx

HTTP authentication with Nginx to password-protect directories on your server or even a whole website

1 Preliminary Note

here with the document root /var/www/ and the Nginx vhost configuration file /etc/nginx/sites-enabled/ The directory I want to password-protect is /var/www/

2 Creating The Password File

a password file where users that should be able to log in are listed with their passwords (in encrypted form). To create such a password file, we can either use Apache’s htpasswd tool, or we use the Python script from

2.1 Using Apache’s htpasswd Command

to use Apache’s htpasswd command, check if it exists on your system

which htpasswd

root@server1:~# which htpasswd

On Debian/Ubuntu, it’s part of the apache2-utils package which we can install

apt-get install apache2-utils

.htpasswd; I just named it .htpasswd because that’s the way password files are named under Apache

htpasswd -c /var/www/ falko

want to add another user without deleting all existing users, use the htpasswd command without the -c switch:

htpasswd /var/www/ till

2.2 Using The Python Script

download it to /usr/local/bin and make it executable

cd /usr/local/bin
chmod 755 /usr/local/bin/

to create the password file /var/www/ now and store the user falko in it -c -b /var/www/ falko falkossecret

use the command without the -c switch -b /var/www/ till tillssecret

3 Configuring Nginx

to add it to our Nginx vhost configuration in /etc/nginx/sites-enabled/, inside the server {} container.

vi /etc/nginx/sites-enabled/

Reload Nginx

/etc/init.d/nginx reload

Leave a comment