htpasswd using openssl

If you search online, how to add Basic Authentication to a Nginx site, you will find most articles refer to using htpasswd, which you may not have on your server if you are using Nginx. Even the Nginx site refers to using htpasswd

There is no reason to add htpasswd if you have openssl on your server, you can use it instead to generate the password. No need to install software that you will never use on the server except maybe a few times.

In this post, I will show how you can accomplish this task using openssl.


Using the command shown below we will generate the password and add it to a .htpasswd file.

printf "<user>:$(openssl passwd -apr1 <your password>)\n" >> /etc/nginx/.htpasswd

Replace <user> with the username and <your password> with the password you wish to set. The output of the command is being sent to /etc/nginx/.htpasswd. You do not have to use the same location as I have done. 

Then inside your sites-enabled/site or in nginx.conf

    location / {                
  auth_basic "Restricted Content";
  auth_basic_user_file /etc/nginx/.htpasswd;

The newly added lines could be in any location block defined either in nginx.conf or a file that defines a site under the conf folder or sites-enabled folder. 

In the example shown here, I am restricting the entire site. If you wish you could have added those lines for a certain path only by specifying something else after location. 

    location ^~ /login/ { 
auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;

This restricts the basic authentication to the path specified after location.

Restart your Nginx server and this change should go into effect.

Photo Credit

Photo by Markus Spiske on Unsplash

Further reading:

Leave a Reply