Nginx htpasswd – how to generate one

Nginx Logo

Every time I want to generate Nginx htpasswd I forget how to do it. This is just for my reference so I don’t have to search for a solution on the Internet. Apache comes with htpasswd utility, but I strictly run Nginx these days and don’t really need Apache or any Apache related utilities on my servers.

I use PHP to generate a hashed password like this:

$ php -a
php > echo crypt('mypassword', base64_encode('mypassword'));
bX6j7x3Ep6RnU

Now add the password in your htpasswd file

echo 'myuser:bX6j7x3Ep6RnU' >> /etc/nginx/htpasswd

Finally add your password file to Nginx config:

location / {
  auth_basic  "Restricted";
  auth_basic_user_file  /etc/nginx/htpasswd;
}

Reload Nginx:

sudo service nginx reload

Thanks Tobias Sjösten for the tip.

Marko