LAMP构建-Apache用户认证(输入密码才能访问)

输入网址后不会直接显示网站,而是提示要求你输入密码才能访问;

编辑httpd-vhosts.conf文档

vim /usr/local/apache2.4/conf/extra/httpd-vhosts.conf
<VirtualHost *:80>
    DocumentRoot "/data/wwwroot/szl.com"
    ServerName szl.com
    ServerAlias www.szl.com
    <Directory /data/wwwroot/szl.com>;            //指定认证的目录
      AllowOverride AuthConfig                           //这个相当于打开认证的开关 
      AuthName "szl.com user auth"                    //自定义认证的名字,作用不大
      AuthType Basic                                            //认证的类型,一般为Basic
      AuthUserFile /data/.htpasswd                      //指定密码文件所在位置
      require valid-user                                        //指定需要认证的用户为全部可用用户
    </Directory>
    ErrorLog "logs/szl.com-error_log"
    CustomLog "logs/szl.com-access_log" common
</VirtualHost>

创建密码文件

创建密码文件与用户名admin

/usr/local/apache2.4/bin/htpasswd -c -m /data/.htpasswd admin

重新加载配置-t,graceful

/usr/local/apache2.4/bin/apachectl -t
/usr/local/apache2.4/bin/apachectl graceful

绑定hosts,浏览器测试

LAMP构建-Apache用户认证(输入密码才能访问)

curl命令服务器本机测试

需要输入账号密码就提示代码401
正常为代码200

curl -x127.0.0.1:80 szl.com

[root@shu-test ~]# curl -x127.0.0.1:80 szl.com
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Unauthorized</title>
</head><body>
<h1>Unauthorized</h1>
<p>This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
</body></html>
[root@shu-test ~]#

针对单个页面文件进行加密

修改httpd-vhosts.conf配置文档

vim /usr/local/apache2.4/conf/extra/httpd-vhosts.conf

<VirtualHost *:80>
    DocumentRoot "/data/wwwroot/szl.com"
    ServerName szl.com
    ServerAlias www.szl.com
#    <Directory /data/wwwroot/szl.com>;
    <FilesMatch admin.php>
      AllowOverride AuthConfig
      AuthName "szl.com user auth"
      AuthType Basic
      AuthUserFile /data/.htpasswd
      require valid-user
     </FilesMatch>
#    </Directory>
    ErrorLog "logs/szl.com-error_log"
    CustomLog "logs/szl.com-access_log" common
</VirtualHost>

创建admin.php文件

vim /data/wwwroot/szl.com/admin.php
[root@shu-test ~]# cat /data/wwwroot/szl.com/admin.php
<?php
echo "admin.php";
?>
[root@shu-test ~]#

测试

测试admin.php
需要输入密码
测试szl.com,不需要账号密码;
LAMP构建-Apache用户认证(输入密码才能访问)