Restrict Access to a website with Apache on Ubuntu
This article will demonstrate how to restrict access to a website for public visitors and allow certain visitors with password authentication in Apache web server itself.
First run below commands to install Apache utilities.
sudo apt-get update
sudo apt-get install apache2-utils
The Apache utilities package allows us to run the htpasswd command to create a hidden password file that can use to authenticate users.
The hidden password file called .htpasswd needs to be created in /etc/apache2 configuration directory.
Run below command to create the file along with an username and it will prompt you to type a password for that user.
sudo htpasswd -c /etc/apache2/.htpasswd username
You can add multiple users running the above command, but remove -c from the command for the next users as -c argument is only to create the .htpasswd file first time.
Now locate the relevant Apache VirtualHost configuration file under the /etc/apache2/sites-enabled/ directory and add the following code and specify the root path for your website then save it. In my case it is /var/www/html
AuthName "Restricted Content"
Sample VirtualHost file:
Run below command to test the VirtualHost file configuration and if you get Syntax OK output your configuration is correct.
sudo apache2ctl configtest
Now restart Apache web server service to effect the change.
Go to your website and it will prompt you to enter the username and password to access the website.
That’s it. ?