Security is always the first priority for everyone and if you are maintaining the security of data then you have a great responsibility for you. If you are a webmaster and you want to limit access to a specific website to the limited person who has the login details only. Then this article will help you to How to Setup Basic Apache Authentication using Virtual Host.
For this article, you must have apache access with full privileges. If you are using shared hosting visit below link to configure the same using .htaccess.
Step 1 – Create Authentication File
Let’s start with creation of users in .htpasswd file. This file will contain user and password information either in plain text or md5 encrypted, which can access the website.
touch /etc/apache2/.htpasswd htpasswd -m /etc/apache2/.htpasswd myuser1 -c :is used only for first time when you create .htpasswd file. Do not use this if .htpasswd already exists else it will recreate file. -m :is used to save password in md5 format.
Let’s create another user using following command..
htpasswd -m /etc/apache2/.htpasswd myuser2
Step 2 – Setup Apache Basic Authentication
You have configured Apache basic authentication using .htaccess file or directly with the Apache Virtual host. In this tutorial, we will configure settings in the Apache virtual host. If you like using .htaccess follow this tutorial.
Let’s edit Apache virtual host configuration file in your favorite text editor. Then add the following configurations in the virtual host block.
Deny from all
#Allow from 127.0.0.1 ##Set IP to allow access without password
AuthName "Restricted Area"
<Location /> :Part of website you want to restrict. / is for retrict full website or you can specify location like /admin or /demo etc. Deny from all :Restrict everyone AuthUserFile :File where users login details are saved. AuthName :Message will be appeared on credentials window. AuthType :Type of authentication to be used. Read more. Satisfy :Interaction between host-level access control and user authentication. Read more. require :Selects which authenticated users can access restricted area on website. Read more
Restart Apache Service
After making any changes in the Apache configuration file (httpd.conf or apache2.conf), you need to restart the Apache web service.
For CentOS/RHEL 6/5 Users:
sudo service httpd restart
For CentOS/RHEL 8/7 Users:
sudo systemctl restart httpd.service
For Ubuntu/Debian Users:
sudo systemctl restart apache2