Setting Up HTTP Basic WEB-Authentication
For Nginx
Install Required Tools
Install the apache2-utils package which includes the htpasswd command:
sudo apt install apache2-utilsCreate a Password File
Generate a .htpasswd file to store usernames and passwords:
sudo htpasswd -c /etc/nginx/.htpasswd your_usernameYou’ll be prompted to enter and confirm the password. The credentials will be saved in an encrypted format in the /etc/nginx/.htpasswd file.
Configure Nginx
Edit your Nginx site configuration file:
sudo nano /etc/nginx/sites-available/defaultAdd the following lines to configure HTTP Basic Authentication for a location block:
server {
...
location / {
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
...
}
...
}Test and Reload Nginx Configuration
After making changes, test the Nginx configuration for syntax errors:
sudo nginx -tReload Nginx to apply the changes:
sudo systemctl reload nginxFor Apache2
Install Required Tools
Similarly, install the apache2-utils package:
sudo apt install apache2-utilsEnable Required Modules
Enable the necessary Apache modules for authentication:
sudo a2enmod auth_basic
sudo a2enmod authn_fileCreate a Password File
Generate a .htpasswd file to store usernames and passwords:
sudo htpasswd -c /etc/apache2/.htpasswd your_usernameYou’ll be prompted to enter and confirm the password. The credentials will be saved in an encrypted format in the /etc/apache2/.htpasswd file.
Configure Apache
Edit your Apache site configuration file:
sudo nano /etc/apache2/sites-available/000-default.confAdd the following lines inside the <VirtualHost *:80> block to configure HTTP Basic Authentication:
<VirtualHost *:80>
...
<Directory "/path/to/your/web/directory">
AuthType Basic
AuthName "Restricted Access"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user
</Directory>
...
</VirtualHost>Test and Restart Apache
Check the Apache configuration for syntax errors:
sudo apache2ctl configtestRestart Apache to apply the changes:
sudo systemctl restart apache2This guide covers the steps to set up HTTP Basic Authentication on both Nginx and Apache2 servers, ensuring secure access to your web applications.