Apache用户认证 :
有时候我们的需求是针对某个站点需要认证后再次访问。例如打开某个网址,首先输入用户名和密码,然后就可以访问其内容了!
vim /usr/local/apache2.4/conf/extra/httpd-vhosts.conf
<VirtualHost *:80>
DocumentRoot "/data/wwwroot/haha.com"
ServerName haha.com
<Directory /data/wwwroot/haha.com> //指定认证的目录
AllowOverride AuthConfig //这个相当于打开认证的开关
AuthName "haha.com user auth" //自定义认证的名字,作用不大
AuthType Basic //认证的类型,一般为Basic,其他类型几乎没用过
AuthUserFile /data/.htpasswd //指定密码文件所在位置
require valid-user //指定需要认证的用户为全部可用用户
</Directory>
</VirtualHost>
/usr/local/apache2.4/bin/htpasswd -c -m /data/.htpasswd zhdy
-c: 创建(create)
-m: md5 加密方式
/data/.htpasswd :指定密码文件位置
zhdy: 用户名
然后回车后我们就要输入一对新的密码!
增加一个zhdy的用户:
[root@zhdy-02 ~]# /usr/local/apache2.4/bin/htpasswd -c -m /data/.htpasswd zhdy
New password:
Re-type new password:
Adding password for user zhdy
检查并重载:
[root@zhdy-02 ~]# /usr/local/apache2.4/bin/apachectl -t
Syntax OK
[root@zhdy-02 ~]# /usr/local/apache2.4/bin/apachectl graceful
[root@zhdy-02 ~]# curl -x127.0.0.1:80 haha.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>
curl -x127.0.0.1:80 haha.com //状态码为401
401意味着你访问的页面需要做用户名密码验证
当我们输入用户名和密码就会出现如下:
welcome access haha.com
curl -x127.0.0.1:80 -uzhdy:passwd haha.com //状态码为200
[root@zhdy-02 ~]# curl -x127.0.0.1:80 -uzhdy:asd9577 haha.com
welcome access haha.com
有时候我们不会整个网站做这样的设置,但是我们往往会选择对一些后台的登录页面做一下二次认证,往往是针对一个页数页面:
咱们刚刚指定的是目录 <Directory /data/wwwroot/haha.com> 只要访问这个目录下的页面都会显示认证。 咱们现在就对某个页面进行二次认证!
<VirtualHost *:80>
DocumentRoot "/data/wwwroot/haha.com"
ServerName haha.com
#<Directory /data/wwwroot/haha.com>
<FilesMatch 123.php>
AllowOverride AuthConfig
AuthName "haha.com user auth"
AuthType Basic
AuthUserFile /data/.htpasswd
require valid-user
</FilesMatch>
#</Directory>
</VirtualHost>
我们先把之前的站点目录注释掉,然后增加<FilesMatch 123.php> 当我们访问站点下的123.php的时候就会出现二次认证
[root@zhdy-02 ~]# /usr/local/apache2.4/bin/apachectl -t
Syntax OK
[root@zhdy-02 ~]# /usr/local/apache2.4/bin/apachectl graceful
[root@zhdy-02 ~]# vim /data/wwwroot/haha.com/123.php
编辑一个123测试页面
然后再次访问测试站点并输入咱们创建的123页面。
[root@localhost ~]# curl -x127.0.0.1:80 www.haha.com/123.php
<!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@localhost ~]# curl -x127.0.0.1:80 -uzhdy:asd9577 www.haha.com/123.php
test use username and passwd
首先第一个我们看到了访问咱们设置特殊的123页面出现了验证;咱们再次加上验证就完美的显示了内容!