有时候我们有这样的需求:有一个网站,其中一个目录只有你自己或者管理员才能看到的,不想让别人去访问,而且,还想在网站去展示,因为方便自己访问,这时候,有必要去做一个用户认证。也就是当你输入用户名和密码之后,只有输入正确了才可以去访问。

## 假如网站下有abc目录,目录有个文件,正常的话,可以访问

[root@aminglinux www]# mkdir abc

[root@aminglinux www]# cp /etc/passwd abc/123.txt

WEBRESOURCE825ac94f3dce19e615d5a6a60555b

## 但比如说我们不想让别人访问网站下的abc目录,这时要做用户认证,编辑虚拟主机配置文件

[root@aminglinux www]# vim /usr/local/apache2/conf/extra/httpd-vhosts.conf

  <Directory /data/www/abc>

       AllowOverride AuthConfig

       AuthName "auth-admin"

       AuthType Basic

       AuthUserFile /data/.htpasswd

       require valid-user

   </Directory>

WEBRESOURCE5849178af196d8ed464c3856cc4b5

[root@aminglinux www]# /usr/local/apache2/bin/apachectl -t

Syntax OK

[root@aminglinux www]# /usr/local/apache2/bin/apachectl graceful

## 创建密码文件

[root@aminglinux www]# /usr/local/apache2/bin/htpasswd -c /data/.htpasswd wyy

New password:

Re-type new password:

Adding password for user wyy

## 查看生成的密码

[root@aminglinux www]# cat /data/.htpasswd

wyy:U6opizopWbwsg

## 查看帮助文档

[root@aminglinux ~]# /usr/local/apache2/bin/htpasswd --help

 -c  Create a new file.

 -n  Don't update file; display results on stdout.

 -m  Force MD5 encryption of the password.

 -d  Force CRYPT encryption of the password (default).

 -p  Do not encrypt the password (plaintext).

 -s  Force SHA encryption of the password.

 -b  Use the password from the command line rather than prompting for it.

 -D  Delete the specified user.

# 再次创建用户,则不需要-c创建密码文件,否则会覆盖

[root@aminglinux ~]# /usr/local/apache2/bin/htpasswd -m /data/.htpasswd wyy1

New password:

Re-type new password:

Adding password for user wyy1

# 修改配置文件测试语法

[root@aminglinux ~]# /usr/local/apache2/bin/apachectl -t

Syntax OK

#重启

[root@Lx ~]#/usr/local/apache2/bin/apachectl restart

## 这时候呢,再访问这个abc目录话,就需要输入用户名与密码

WEBRESOURCEa38df89dee74723d05d07eced21d5