Apache is a free, open-source webserver. Any user can access your application over the Internet when it is hosted on an Apache webserver.
In some cases, you might need to secure your application, that only authenticated users can access the application hosted on your server. You can protect your application by using Apache htpasswd.
1. Connect to your server as a root and update your base system with the latest available packages:
apt-get update -y
2. Install Apache:
apt-get install apache2 apache2-utils -y
3. After installing Apache, run the following commands to start the Apache service and enable it to start after system reboot:
systemctl start apache2
systemctl enable apache2
4. Then open your browser and navigate to the URL http://your-server-ip. You should see your default Apache web page:
5. Now you need to create a password file so that Apache can use to authenticate users. You can create a hidden .htpasswd file withing /etc/apache2 directory for a user named test_user using the htpasswd utility:
htpasswd -c /etc/apache2/.htpasswd test_user
6. Enter the chosen password for your test_user:
This will create a .htpasswd file with user credentials. Those credentials will be used to access your site.
7. Now you need to create a directory for your website with the following command. Instead of "domain_name" use your own domain:
mkdir /var/www/html/domain_name
8. Now create an index.html file inside your web directory:
nano /var/www/html/domain_name/index.html
9. Add the following content there:
10. Change the ownership of your web directory to www-data:
chown -R www-data:www-data /var/www/html/domain_name
11. Now you need to create an Apache virtual host configuration file for your website and define basic authentication:
nano /etc/apache2/sites-available/domain.conf
12. There add the following lines:
<VirtualHost *:80>
ServerName domain_name
ServerAdmin webmaster@domain_name
DocumentRoot /var/www/html/domain_name
DirectoryIndex index.html
ErrorLog ${APACHE_LOG_DIR}/domain_name-error.log
CustomLog ${APACHE_LOG_DIR}/domain_name-access.log combined
<Directory "/var/www/html/domain_name">
Options -Indexes +FollowSymLinks
AllowOverride None
AuthType Basic
AuthName "Restricted Content"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user
</Directory>
</VirtualHost>
13. Ater that, check the Apache for any syntax errors with the following command:
apachectl -t
You should get the output:
14. Enable the Apache virtual host file for your website with the following command:
a2ensite domain.conf
15. Restart Apache:
systemctl restart apache2
Now your site should be secured with Apache basic authentication. To check it, open your web browser and type the URL http://domain_name. (Your domain name)
Enter your username and password and click on the Sign in button. You should see your website default page: