Instructions for configuring Basic Authentication on Nginx

Tram Ho

During web development, there are times when we will need to limit user access to our website and to limit we can require users to authenticate via tài khoản and mật khẩu .

This article will guide you through the steps to configure Basic Authentication to protect Nginx server running on Ubuntu Server environment.


  1. Prepare 1 VPS Ubuntu Server
  2. Install Nginx as a web server

Create a file to save passwords

To generate a password we can use OpenSSL .

If the server already has OpenSSL , you can move on to the next step, if not, we need to install OpenSSL first via the command:

Create a .htpasswd file to store the username and password inside the /etc/nginx/basic-auth directory. If there are multiple websites running on this server, you can create separate files for each web site, for example .htpasswd-web , .htpasswd-another-web .

First we will add the login name to the .htpasswd file. For example, we use the username as username , then run the command:

Next we need to add an encrypted password for the username with the command:

After running the above command, enter the desired password and confirm the password and then press Enter .

View the content of the newly created .htpasswd file, run the command:

The content has the form below, which means we have successfully created an account and password:

Configure Password Authentication for Nginx

Update the nginx config file, in this example I use the default file of nginx, in addition, people can update the config file corresponding to the web on their server.

Initially the file /etc/nginx/sites-enabled/default has the following form:

We add auth_basic and auth_basic_user_file pointing to the username and password file you just created above.

Save the config file and restart the server.

After restarting the server, accessing our website, we will see a pop-up window asking for a username and password (like the image at the beginning of the article). If we enter the correct account, we will be allowed to access the inside of the website. Otherwise, if you enter it incorrectly or choose to cancel , the website will automatically redirect to the 401 Authorization Required error page.

Share the news now

Source : Viblo