In this tutorial we will cover the steps needed to set up HTTP Authentication on a Linux server with Nginx.

Requirements

* Linux server with installed CentOS, Ubuntu or Debian

* Nginx installed on the server (How to install Nginx)

Configuration

In order to set up HTTP Authentication for a directory, we will use the htpasswd command to create an encrypted user and password. In order to make the command available we will need to install the following package:

For CentOS:

yum install httpd-tools

For Ubuntu/Debian:

sudo apt-get install apache2-utils

Once we have the package installed, we can proceed with the creation of our .htpasswd file which will contain the information about the username and the password:

htpasswd -c /path/to/directory/.htpasswd username

In the command above, the options that we used are:

/path/to/directory – the full path to the directory that we want to set authentication for
username – the username that we will use for authentication

After we execute the command, we will be prompted to enter and re-enter a password for the user.

We are now ready with setting up the user. The only thing left is to modify the Nginx configuration to use the .htpasswd file. In our case we will use the default Nginx configuration files. Please note that your domain config may have a different name.

For CentOS:

vim /etc/nginx/conf.d/default.conf

For Ubuntu/Debian:

vim /etc/nginx/sites-available/default

We will need to add 2 lines to the configuration. After the changes, the content of the file should look like this:

The lines that we added are:

The first one defines the text that we will see in the login box which will appear when we access the folder using a browser.

The second one contains the path to our .htpasswd file where the username and the password are stored.

The last thing we need to do is to save the changes and restart the Nginx service:

/etc/init.d/nginx restart