Learn how to secure your Nginx server with password authentication. This step-by-step guide covers installing necessary tools, creating a .htpasswd file, configuring Nginx, and testing your setup to ensure your website is protected.

How To Set Up Password Authentication with Nginx

Prerequisites

  1. A server running Ubuntu 22.04 with a non-root user with sudo privileges.
  2. Nginx installed on your server.
  3. OpenSSL installed on your server.

Step 1: Install Nginx and OpenSSL

If you haven’t already installed Nginx and OpenSSL, you can do so using the following commands:

sudo apt update
sudo apt install nginx openssl

Step 2: Create the Password File

Nginx uses a file called .htpasswd to store usernames and passwords. We’ll use the openssl command to create this file.

  1. Create the .htpasswd file with a username. Replace your_username with your chosen username:
   sudo sh -c "echo -n 'your_username:' >> /etc/nginx/.htpasswd"
  1. Add a password for the user. Replace your_password with your chosen password:
   sudo sh -c "openssl passwd -apr1 >> /etc/nginx/.htpasswd"

You’ll be prompted to enter and confirm the password. This command will generate a hashed password and append it to the .htpasswd file.

Step 3: Configure Nginx to Use the Password File

Next, we’ll configure Nginx to use the .htpasswd file for authentication.

  1. Open your Nginx configuration file. This could be the default server block file or a specific site configuration file. For example:
   sudo nano /etc/nginx/sites-available/default
  1. Inside the server block, add the following lines to configure the location you want to protect. This example protects the entire site:
   server {
       listen 80;
       server_name your_domain;

       location / {
           auth_basic "Restricted Area";
           auth_basic_user_file /etc/nginx/.htpasswd;
           # other configuration options
       }

       # other server block settings
   }
  1. Save and close the file.

Step 4: Test Nginx Configuration

Before reloading Nginx to apply the changes, it’s a good idea to test the configuration for syntax errors:

sudo nginx -t

If the output shows syntax is ok and test is successful, you can proceed to reload Nginx.

Step 5: Reload Nginx

Reload Nginx to apply the changes:

sudo systemctl reload nginx

Step 6: Verify the Authentication

Open your web browser and navigate to your site. You should be prompted to enter a username and password. Use the credentials you set up in the .htpasswd file. If you enter the correct credentials, you should be granted access to the site.

Conclusion

You have successfully set up password authentication with Nginx. This adds an extra layer of security to your site by requiring a username and password to access protected areas.