Authenticating with Password in Apache and Nginx on Raspberry Pi OS

Posted by Asia VPN on February 09, 2024 · 2 mins read

Authenticating with Password in Apache and Nginx on Raspberry Pi OS

In this guide, we'll learn how to set up password authentication in both Apache and Nginx on Raspberry Pi OS (Debian).

Prerequisites

Before you begin, make sure you have:

  • A Raspberry Pi running Raspberry Pi OS (Debian).
  • Apache and Nginx installed and configured.

Setting Up Password Authentication in Apache

Step 1: Create a Password File

First, create a password file using the htpasswd utility. Replace username1 and username2 with the desired usernames:

htpasswd -c /etc/apache2/.htpasswd username1
htpasswd /etc/apache2/.htpasswd username2
    

Step 2: Configure Apache

Edit the Apache configuration file:

sudo nano /etc/apache2/sites-available/000-default.conf
    

Add the following lines inside the <VirtualHost> section:

        <Directory "/var/www/html">
            Options Indexes FollowSymLinks
            AllowOverride All
            Require all granted
            AuthType Basic
            AuthName "Restricted Content"
            AuthUserFile /etc/apache2/.htpasswd
            Require valid-user
        </Directory>
    

Step 3: Restart Apache

Restart the Apache service to apply the changes:

sudo systemctl restart apache2
    

Step 4: Access Restricted Content

Now, when you access your website, you'll be prompted to enter the username and password you created in Step 1.

Setting Up Password Authentication in Nginx

Step 1: Create a Password File

Similar to Apache, create a password file using the htpasswd utility:

sudo htpasswd -c /etc/nginx/.htpasswd username1
sudo htpasswd /etc/nginx/.htpasswd username2
    

Step 2: Configure Nginx

Edit the Nginx configuration file:

sudo nano /etc/nginx/sites-available/default
    

Add the following lines inside the server block:

        location / {
            auth_basic "Restricted Content";
            auth_basic_user_file /etc/nginx/.htpasswd;
        }
    

Step 3: Restart Nginx

Restart the Nginx service to apply the changes:

sudo systemctl restart nginx
    

Step 4: Access Restricted Content

Now, accessing your website in Nginx will prompt you to enter the username and password you created in Step 1.

Conclusion

Congratulations! You've successfully set up password authentication in both Apache and Nginx on Raspberry Pi OS. This adds an extra layer of security to your web servers.