nginx的用户认证
1).nginx的用户认证功能:
当访问一些私密资源时,最好配置用户认证,增加安全性。
2)nginx用户认证步骤和示例
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
http {
...
include vhost/*.conf; #添加
}
[root@localhost ~]# cat /usr/local/nginx/conf/vhost/www.1.conf
server{
listen 80;
server_name www.1.com;
root /data/wwwroot/www.1.com;
index index.html;
location /admin/
{
auth_basic "Authtest";
auth_basic_user_file /usr/local/nginx/conf/htpasswd; #指定加密密码文件位置
}
}
[root@localhost ~]# mkdir /data/wwwroot/www.1.com/admin
[root@localhost ~]# echo "admin_index" > /data/wwwroot/www.1.com/admin/index.html
[root@localhost ~]# yum -y install httpd #安装一个生成密码文件的命令工具htpasswd
使用htpasswd生成加密密码文件htpasswd,下面指定密码文件,shi是定义的用户名,通过给用户名设置密码
[root@localhost ~]# htpasswd -c /usr/local/nginx/conf/htpasswd shi #回车后,即可给用户名shi设置密码:123
[root@localhost ~]# htpasswd -c /usr/local/nginx/conf/htpasswd shi #注意:增加用户不要加-c,如:
New password: #输入密码123
Re-type new password: #确认密码123
Adding password for user shi
[root@localhost ~]# cat /usr/local/nginx/conf/htpasswd
shi:$apr1$D1lGJ8mP$4fP/SRO1V0zNY9Jb31SRJ.
#注意:增加用户不要加-c,否则会覆盖之前的,增加新用户和修改用户密码都是如下:
[root@localhost ~]# htpasswd /usr/local/nginx/conf/htpasswd shi2
New password:
Re-type new password:
Adding password for user shi2
[root@localhost ~]# cat /usr/local/nginx/conf/htpasswd
shi:$apr1$D1lGJ8mP$4fP/SRO1V0zNY9Jb31SRJ.
shi2:$apr1$qd7JB1.S$1id1mgg5ye/Tn.F3vLYve1
[root@localhost ~]# /usr/local/nginx/sbin/nginx -s reload
浏览器访问: 192.168.171.132/admin/
输入用户名和密码:shi/123
curl使用用户名和密码访问网站:# curl -ushi:123 www.1.com/admin/index.html
nginx的用户认证参考链接: https://github.com/aminglinux/nginx/blob/master/access/auth.md