How to Password Protect Directory Using NGINX


password protect directory nginx

Sometimes, you may need to protect confidential or sensitive information on your website from unauthorized users. NGINX allows you to password protect directories and subdirectories on your site so only users with appropriate credentials can access them. Here’s how to password protect directory using NGINX.

 

How to Password Protect Directory Using NGINX

Here are the steps to password protect directory using NGINX.

 

1. Log into your Server

Log into your server using SSH, or open a terminal on your Linux system. Navigate to your user directory. Ensure that you have a subdirectory in it, for your website (example.com). If it doesn’t exist create it with the following command


$ mkdir -p nginx/example.com
$ cd /home/username/example.com

 

2. Create basic_auth.conf file

In this folder, create a file named basic_auth.conf


$ sudo vim basic_auth.conf

Add the following lines to it.


location / {
  auth_basic "Restricted";
  auth_basic_user_file /home/username/nginx/example.com/.htpasswd;
}

 

In the above commands,

  • auth_basic – specifies the title of prompt that users see for authentication
  • auth_basic_user_file – location of password file.

Since we mention location directive as ‘/’ the password authentication is applicable for the entire website. You can change it to be for the specific directories you want. For example,


location /subdirectory/

 

3. Create .htpasswd file

Use the htpasswd command to create a password file and add users to it.


$ htpasswd -c /home/username/nginx/example.com/.htpasswd LOGIN

LOGIN is the username that is authorized to access your directory.

You will be asked to enter password twice for confirmation.

 

4. Reload NGINX

Reload NGINX server to apply changes.


$ sudo service nginx reload

 

5. Test your configuration

Open a web browser and navigate to the directory you have password protected. In the above example, it is the root directory.

You will be asked to enter username & password. If you enter the right credentials, you will be directed to your website. Otherwise, you will see a “403: Access Forbidden” error message.

 

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!