How To Protect Directory With Password on Nginx

Protect Directory With Password on Nginx

In this tutorial, we will show you how to protect a directory with a password on Nginx. For those of you who didn’t know, unlike Apache, Nginx does not have any .htaccess file. Password protection is achieved by using the Nginx HttpAuthBasic module directives in the configuration file. For future reference, I will show you steps to protect the directory with a password on Nginx.

This article assumes you have at least basic knowledge of Linux, know how to use the shell, and most importantly, you host your site on your own VPS. The installation is quite simple and assumes you are running in the root account, if not you may need to add ‘sudo‘ to the commands to get root privileges. I will show you through the step-by-step Protect Directory With Password on Nginx.

Protect Directory With Password on Nginx

Step 1. First, add the following to your Nginx configuration file:

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

Step 2. Create the htpasswd file, notice that the file is /etc/nginx/htpasswd. This means you need to use htpasswd to create that file:

htpasswd -c /etc/nginx/htpasswd yourusername
New password: 
Re-type new password: 
Adding password for user yourusername

This will create the password file.

Step 3. Next restart Nginx’s configuration:

service nginx restart

Now when you visit your directory or domain, you will be asked to enter a username and password that you chose beforehand. This is definitely not the most secure way of restricting domain access.

Congratulations! You have successfully protected the directory on Nginx. Thanks for using this tutorial to protect the directory with passwords on the Nginx system. For additional help or useful information, we recommend you check the official Nginx website.

Nginx Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “Nginx Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!