Skip to content

Basic Auth

To create username-password pairs, use a password file creation utility, for example, apache2-utils or httpd-tools

Verify that apache2-utils (Debian, Ubuntu) or httpd-tools (RHEL/CentOS/Oracle Linux) is installed.

Create a password file and a first user. Run the htpasswd utility with the -c flag (to create a new file), the file pathname as the first argument, and the username as the second argument:

Bash
sudo htpasswd -c /etc/apache2/.htpasswd user1

Press Enter and type the password for user1 at the prompts.

Create additional user-password pairs. Omit the -c flag because the file already exists:

Bash
sudo htpasswd /etc/apache2/.htpasswd user2

You can confirm that the file contains paired usernames and hashed passwords:

Bash
$ cat /etc/apache2/.htpasswd
user1:$apr1$/woC1jnP$KAh0SsVn5qeSMjTtn0E9Q0
user2:$apr1$QdR8fNLT$vbCEEzDj7LyqCMyNpSoBh/
user3:$apr1$Mr5A0e.U$0j39Hp5FfxRkneklXaMrr/

Configuring NGINX and NGINX Plus for HTTP Basic Authentication Inside a location that you are going to protect, specify the auth_basic directive and give a name to the password-protected area. The name of the area will be shown in the username/password dialog window when asking for credentials:

Nginx Configuration File
location /api {
    auth_basic "Administrator’s Area";
    #...
}

Specify the auth_basic_user_file directive with a path to the .htpasswd file that contain user/password pairs:

Nginx Configuration File
location /api {
    auth_basic           "Administrator’s Area";
    auth_basic_user_file /etc/apache2/.htpasswd; 
}

Alternatively, you you can limit access to the whole website with basic authentication but still make some website areas public. In this case, specify the off parameter of the auth_basic directive that cancels inheritance from upper configuration levels:

Nginx Configuration File
server {
    ...
    auth_basic           "Administrator’s Area";
    auth_basic_user_file conf/htpasswd;

    location /public/ {
        auth_basic off;
    }
}

Taken from here