To restrict access to certain HTTP resources, create two files: .htaccess and .htpasswd (or equivalent per httpd.conf setting).
By default Apache does not allow the use of .htaccess files.
Editing the Apache config file:
sudo vi /etc/httpd/conf/httpd.conf
Find the section that begins with <Directory “/var/www/html”>.
Change the line from AllowOverride none to AllowOverride AuthConfig.
AllowOverride AuthConfig
Save and close the file.
The htpasswd command is used to create and update the files used to store usernames and password for basic authentication of Apache users.
For example, create a .htpasswd file for user1.
sudo htpasswd -c /etc/httpd/.htpasswd user1
This will prompt to supply and confirm a password for user1.
WARNING: Only use -c the first time the file is created.
Create another user named user2:
sudo htpasswd /etc/httpd/.htpasswd user2
sudo cat /etc/httpd/.htpasswd
returns:
user1:$apr1$0r/2zNGG$jopiWY3DEJd2FvZxTnugJ/ user2:$apr1$07FYIyjx$7Zy1qcBd.B8cKqu0wN/MH1
sudo chown apache:apache /etc/httpd/.htpasswd sudo chmod 0660 /etc/httpd/.htpasswd
Create a .htaccess file in the web directory which is to be restricted.
For example, create the .htaccess file in the /var/www/html/ directory to restrict the entire document root.
sudo vi /var/www/html/.htaccess
Add the following content:
AuthType Basic AuthName "Restricted Content" AuthUserFile /etc/httpd/.htpasswd Require valid-user
Save and close the file, then restart Apache to make these changes take effect.
sudo apachectl restart
Try to access the restricted content in a web browser by visiting the URL or static IP address.
This will prompt for a username and password to access the website.
NOTE: If the correct credentials are entered, the site will be accessible.