Nginx is a popular web server that is often used to host web applications. In this article, we will guide you through the process of setting up password authentication with Nginx on Ubuntu 20.04.
Before we begin, make sure that you have a fresh installation of Ubuntu 20.04 and that Nginx is installed on your system. You will also need to be logged in as a user with sudo
privileges.
Create an Nginx password file
The first step is to create an Nginx password file that will store the username and password for the user that we want to authenticate. To do this, open a terminal and run the following commands:
sudo mkdir /etc/nginx/passwd
sudo htpasswd -c /etc/nginx/passwd/passwords username
Make sure to replace "username"
with the username that you want to use for authentication. When prompted, enter a password for the user and confirm it.
Configure Nginx to use the password file
Next, we need to configure Nginx to use the password file that we just created. To do this, open the Nginx configuration file using the following command:
sudo nano /etc/nginx/nginx.conf
In the file, find the location block that you want to protect with password authentication and add the following code inside it:
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/passwd/passwords;
This code tells Nginx to use the password file that we created earlier for authentication and to display the message "Restricted Area"
to the user when they are prompted for their username and password. Save the file and exit the editor.
Restart Nginx
After making changes to the Nginx configuration file, we need to restart Nginx for the changes to take effect. To do this, run the following command in the terminal:
sudo systemctl restart nginx
Test password authentication
To verify that password authentication is working properly, visit the location that you protected with password authentication in your web browser. You should be prompted for your username and password. Enter the username and password that you created earlier and click "OK"
.
If everything is working correctly, you should be able to access the location and view its content. If you entered the wrong username or password, you should see an "Access denied"
message.
Congratulations! You have successfully set up password authentication with Nginx on Ubuntu 20.04. You can now use this technique to protect sensitive locations on your web server.