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/www.example.com/web/ and the Nginx vhost configuration file /etc/nginx/sites-enabled/www.example.com.vhost. The directory I want to password-protect is /var/www/www.example.com/web/test/.

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 http://trac.edgewall.org/browser/trunk/contrib/htpasswd.py.

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
/usr/bin/htpasswd
root@server1:~#

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/www.example.com/.htpasswd falko

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

htpasswd /var/www/www.example.com/.htpasswd till

2.2 Using The htpasswd.py Python Script

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

cd /usr/local/bin
wget http://trac.edgewall.org/export/10791/trunk/contrib/htpasswd.py
chmod 755 /usr/local/bin/htpasswd.py

to create the password file /var/www/www.example.com/.htpasswd now and store the user falko in it

htpasswd.py -c -b /var/www/www.example.com/.htpasswd falko falkossecret

use the htpasswd.py command without the -c switch

htpasswd.py -b /var/www/www.example.com/.htpasswd till tillssecret

3 Configuring Nginx

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

vi /etc/nginx/sites-enabled/www.example.com.vhost

Reload Nginx

/etc/init.d/nginx reload

Leave a comment