Configuring Basic Authentication in Nginx

I will consider an example of setting up basic authorization in Nginx for a WordPress site. I need the authorization window to pop up for the following pages:

  • http://www.tech-notes.net/wp-admin
  • http://www.tech-notes.net/wp-login.php

To do this, you first need to install apache2-utils. Linux Ubuntu installed on the server:

apt-get install apache2-utils

In the case of CentOS:

yum install httpd-tools

This set of utilities is needed to generate a file with a password and username. I created a folder to store files like this:

mkdir /etc/nginx/auth

Next we generate the password itself:

htpasswd -cmb /etc/nginx/auth/.htpasswd **user password**

Change the user and password values ​​to the desired username and password.

Next, edit the nginx virtual host configuration file with the following lines:

location /wp-admin {
  auth_basic "Restricted";
  auth_basic_user_file /etc/nginx/auth/.ht.passwd_wpadmin;
}

location /wp-login\.php {
  auth_basic "Restricted";
  auth_basic_user_file /etc/nginx/auth/.ht.passwd_wpadmin;
}