HTML Protection

Use the Apache web server with .htaccess and .htpasswd files to protect the access to HTML pages.

1. Create a .htpasswd Password File

Use the htpasswd utility to create a new password file and add a user. Replace username with the username to be added:

sudo htpasswd /etc/apache2/.htpasswd username

In case it is the first user use this command with flag -c to also create a file containing usernames and encrypted passwords:

sudo htpasswd -c /etc/apache2/.htpasswd username

Delete the user username from .htpasswd:

sudo htpasswd -D /etc/apache2/.htpasswd username

2. Create an .htaccess File

In the directory containing the HTML files create an .htaccess file if it doesn’t already exist.

sudo nano /var/www/html/.htaccess

This file will specify the access control rules. Add the following lines to the .htaccess file:

AuthType Basic
AuthName "Restricted Access"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user

3. Enable .htaccess

By default, Apache doesn’t allow .htaccess files to override settings. Enable this by editing the Apache configuration file:

sudo nano /etc/apache2/apache2.conf

Find the <Directory> section for the directory (usually /var/www/html) and change AllowOverride None to AllowOverride All.

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

Save the file and exit.


4. Restart Apache

After making these changes, restart the Apache service to apply the new configuration:

sudo systemctl restart apache2

When someone tries to access the HTML pages from the web server, they will be prompted for a username and password.

Remember to replace /var/www/html with the actual directory where the HTML files are located. Additionally, ensure that .htpasswd file is not accessible from the web, as it contains sensitive information.


5. Disable .htaccess Protection

Open the .htaccess file in the protected directory:

sudo nano /var/www/html/.htaccess

Comment out the auth directives:

# AuthType Basic
# AuthName "Restricted Area"
# AuthUserFile /full/path/to/.htpasswd
# Require valid-user

After making these changes, restart the Apache service to apply the new configuration:

sudo systemctl restart apache2