Search This Blog

Friday, 5 February 2021

How To Set Up Password Authentication with Apache on Linux

 Step 1) Install Apache, start httpd service and create a test page

[root@master ~]# yum install httpd -y

[root@master ~]# systemctl enable httpd

[root@master ~]# systemctl start httpd

[root@master ~]# mkdir -p /var/www/html/test

[root@master ~]# cat>/var/www/html/test/index.html

This is a test page

[root@master ~]# curl -Ik http://master/test/index.html
HTTP/1.1 200 OK
Date: Fri, 05 Feb 2021 08:46:42 GMT
Server: Apache/2.4.37 (centos)
Last-Modified: Fri, 05 Feb 2021 08:42:05 GMT
ETag: "14-5ba92cb7ae0f7"
Accept-Ranges: bytes
Content-Length: 20
Content-Type: text/html; charset=UTF-8

Step 2) Create a password file

[root@master ~]# htpasswd -c /etc/httpd/.htpasswd  pavan
New password:
Re-type new password:
Adding password for user pavan

[root@master ~]# cat /etc/httpd/.htpasswd
pavan:$apr1$2WgAQbfQ$YOdb.nVK5Ywm/fNqC3wZq/

Step 3) Configure Apache password authentication

[root@master ~]# cat>/var/www/html/test/.htaccess
AuthType Basic
AuthName "Password Required"
AuthUserFile /etc/httpd/.htpasswd
Require valid-user

Step 4) Configure httpd.conf to restrict the access to the Document Root Directory

[root@master ~]# vi /etc/httpd/conf/httpd.conf

<Directory "/var/www">
    AllowOverride All
    # Allow open access:
    Require all granted
</Directory>

<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride All
    AuthType Basic
    AuthName "Password Required"
    AuthUserFile /etc/httpd/.htpasswd
    Require valid-user
</Directory>


Step 5) Restart httpd service 

[root@master ~]# systemctl restart httpd

Step 6) Confirm the password authentication

[root@master ~]# curl -Ik http://master/test

HTTP/1.1 401 Unauthorized

Date: Fri, 05 Feb 2021 09:13:29 GMT

Server: Apache/2.4.37 (centos)

WWW-Authenticate: Basic realm="Password Required"

Content-Type: text/html; charset=iso-8859-1


[root@master ~]# curl -u pavan http://master/test

Enter host password for user 'pavan':

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<html><head>

<title>301 Moved Permanently</title>

</head><body>

<h1>Moved Permanently</h1>

<p>The document has moved <a href="http://master/test/">here</a>.</p>

</body></html>

Step 7) You may access the URL on the browser for testing





No comments: