在某些场景下,网站页面的内容需要特殊授权用户才能查看。要实现这个功能,需要在Apache上做设置认证用户。


1、编辑虚拟主机配置

[root@juispan ~]# vi /usr/local/apache2.4/conf/extra/httpd-vhosts.conf
<VirtualHost *:80>
    DocumentRoot "/data/www/abc.com"
    ServerName abc.com
    <Directory /data/www/abc.com>             ##指定认证的目录
        AllowOverride AuthConfig              ##打开认证开关
        AuthName "abc.com user auth"          ##定义认证的名字
        AuthType Basic                        ##指定认证的类型
        AuthUserFile /data/.htpasswd          ##指定密码文件所在的位置
        require valid-user                    ##指定需要认证的用户
    </Directory>
</VirtualHost>


2、增加用户

[root@juispan ~]# /usr/local/apache2.4/bin/htpasswd -c -m /data/.htpasswd juispan
New password:                                  ##“-c”=create “-m”=md5
Re-type new password:                          ##“/data/.htpasswd”=密码存放路径
Adding password for user juispan
[root@juispan ~]# cat /data/.htpasswd 
juispan:$apr1$5UVKQ8Ux$8tkRftVA0ueh7qtD6tzlz1


3、检查重新加载

[root@juispan ~]# /usr/local/apache2.4/bin/apachectl -t
Syntax OK
[root@juispan ~]# /usr/local/apache2.4/bin/apachectl graceful


4、测试验证

本机验证:

[root@juispan ~]# curl -x127.0.0.1:80 abc.com
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Unauthorized</title>                      ##401 未认证
</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@juispan ~]# curl -x127.0.0.1:80 -ujuispan:hao123.com abc.com
abc.com

远端验证:

[LAMP]Apache用户认证_apache

    输入正确的用户名口令后即可显示网页内容。


如果针对的不是整个目录,而是单个网页,可以使用FilesMatch替换Directory,如<FilesMatch 1.php> 。

▎参考配置:

<VirtualHost *:80>
    DocumentRoot "/data/www/abc.com"
    ServerName www.abc.com
    <FilesMatch 1.php>
        AllowOverride AuthConfig
        AuthName "abc.com user auth"
        AuthType Basic
        AuthUserFile /data/.htpasswd
        require valid-user
    </FilesMatch>
</VirtualHost>