一、安装 htpasswd 工具
yum install httpd-tools -y
创建用户文件并设置用户名和密码,并把用户名、密码保存到指定文件中:
[root@ ~]# cd /usr/local/nginx/conf
[root@ conf]# mkdir passwd
[root@ conf]# htpasswd -c /usr/local/nginx/conf/passwd/passwd test
New password:
Re-type new password:
Adding password for user test
注意:test是用户名,你可以根据需要自行设置成其它用户名。运行命令后,会要求你连续输入两次密码。输入成功后,会提示已经为test这个用户添加了密码。
查看下生成的密码文件的内容:
[root@ conf]# cat passwd/passwd
test:$apr1$o6psZOCn$APl2zscV0JYwsR8Lol2tP1
其中用户名就是test,分号后面就是密码(已经加过密)。
1. 新增用户或修改密码
htpasswd -b /usr/local/nginx/conf/passwd/passwd 用户名 密码
2. 删除用户
htpasswd -D /usr/local/nginx/conf/passwd/passwd 用户名
二、修改 nginx 配置文件
找到 nginx 配置文件,因为我们要对整个站点开启验证,所以在配置文件中的第一个server修改如下:
server {
listen 80;
server_name localhost;
.......
#新增下面两行
auth_basic "Please input password"; #这里是验证时的提示信息
auth_basic_user_file /usr/local/nginx/conf/passwd/passwd; # 这里是密码文件,可以填写绝对路径
location /{
.......
}
然后重启 nginx:
service nginx restart
以上都配置无误后,你重新访问你的站点,如果出现需要身份验证的弹窗就说明修改成功了。