How to Setup HTTP Authentication with nginx on Debian

HTTP AuthenticationSometimes you may want to lock specific directory on your ningx server with a password to improve security. For example, you may want to lock your wp-admin directory of your WordPress installation with a password.

Prerequisites

To enable HTTP Authentication with nginx on Debian, you?ll need to have a VPS with root access and nginx server installed in it.

Install Apache Uitls

You?ll need to create and generate an encrypted password for the user using Basic Authentication. For this purpose, we?ll need to install apache uitls. Install apache2-utils with the following command:

Create User and Password

Now you?ll need to create a .htpasswd file that will contain your login credentials. The following command will create the user and encrypt the password and also will add the user and encrypted user to .htpasswd file:

Here we?re locking our wp-admin directory. Replace ?youruser? with your desired username and the path /var/www/example.com/wp-admin/.htpasswd with your desired directory path.

If you open up the .htpasswd file, it?ll look like

Update nginx configuration

Now, you?ll need to let nginx know that you want to activate HTTP Authorization for specific directory.

To do so, open up your nginx configuration file for your website. It should be in /etc/nginx/sites-available/ directory. The configuration file is named as default, if you didn’t change.

However, open the configuration file:

Replace ?default? with your configuration file name.

Add the following code blocks under sever block.

 

Reload nginx

Reload your nginx to see the change effects:

Now, try to access your restricted directory with your browser, you should get a prompt that is asking for the login.

HTTP Authentication

Provide the correct login credentials and access the restricted directory!

Cheers!