We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

HTTP Basic Authentication in Nginx

HTTP Basic Authentication in Nginx. You can restrict access to your website or some parts of it by implementing a username/password authentication.

HTTP Basic authentication can also be combined with other access restriction methods, for example restricting access by geographical location.

Prerequisites

  1. A running Compute Engine, see the Setting up Compute Engine Instance with Ubuntu 18.04.
  2. Initial Ubuntu Server Set up.
  3. Nginx Web Server installed on Ubuntu.

Install Apache Tools

The apache2-utils package provides the htpassword command to configure the password that will restrict access to the target website. So, let’s install the package.

sudo apt install apache2-utils

Set Up Authentication Credentials

The password and the associated username will be stored in a file that you specify while creating the credentials.

The password will be encrypted.

Here we use the file /home/username/directory_name/.htpasswd and the username as nginx_auth

To create the authentication credentials run the following command.

sudo htpasswd -c /home/username/directory_name/.htpasswd nginx_auth

You will be prompted to enter a new password. Enter a secure password and re-enter to confirm.

Now the authentication credentials will get saved in the .htpasswd file.

This is the syntax of the saved credentials.

username:encrypted_password

Configure Nginx

HTTP basic authentication is made possible by the auth_basic and auth_basic_user_file directives.

Edit your Nginx configuration and add the following code for the pages to have the authentication.

sudo nano /etc/nginx/sites-available/yourdomainname.com

Add the below code so that your location block looks similar to the below.

location / {
try_files $uri $uri/ /index.php?$args;

auth_basic "Private Area";
auth_basic_user_file /home/username/directory_name/.htpasswd;
}

Now, if you visit your website you will be prompted to enter your username and password to access the website.

Update Authentication Password

You can use the same command without the -c flag and the username to change the password.

sudo htpasswd /home/username/directory_name/.htpasswd username

You can also create more credentials using this command.

Conclusion

Now you have learned how to set up Basic HTTP Authentication using Nginx on Ubuntu 18.04.

If you have anything to discuss please post your comment below. Thank you!

Cart

Your Cart is Empty

Back To Shop