NginX Password Protect a Web Directory

To password protect a specific web directory, you need to create a username and password in your server and store that in encrypted form in a secured htpasswd file. So let’s create the file using the following commands. Make sure you replace the NewUserName and NewPassword with your desired username and password for accessing the protected folder. :

sudo apt-get install apache2-utils
htpasswd -b /usr/ssl/htpasswd NewUserName NewPassword

Now add the following configuration in the relevant server block. I’m assuming you’ll password protect the adminpanel directory in your web server root directory. Please change this to your own directory. So the configuration you’ll be adding will look like:

location ^~ /adminpanel/
    auth_basic            "Restricted";
    auth_basic_user_file  /usr/ssl/htpasswd;

Now reload your nginx configuration:

sudo service nginx reload