How to Setup HTTP Authentication with nginx on Debian

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


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:

sudo apt-get install apache2-utils

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:

sudo htpasswd -c /var/www/ youruser

Here we’re locking our wp-admin directory. Replace “youruser” with your desired username and the path /var/www/ with your desired directory path.

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

youruser: yourencryptedpassword

Update nginx configuration

Now, you’ll need to let nginx know that you want to activate HTTP Authorization for a 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:

sudo nano /etc/nginx/sites-available/default

Replace “default” with your configuration file name.

Add the following code blocks under sever block.

location /wp-admin {
  auth_basic "Access Restricted";
  auth_basic_user_file /var/www/;

Reload nginx

Reload your nginx to see the change effects:

sudo service nginx reload

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

Provide the correct login credentials and access the restricted directory!