一、添加登录权限
1.参数示例:
location / {
auth_basic "Restricted";
auth_basic_user_file /usr/local/nginx/conf.d/auth-conf/root-123456-conf;
}
这组参数也可以放在server{}模块下,表示整个server下面的所有location都需要经过权限验证才可访问。
2.参数解析:
auth_basic
:两种值,第一个off
表示访问该location不需要认证,第二是任意的字符串值,例如上面的"Restricted"
,这个字符串会在某些情况下展示给用户。
auth_basic_user_file :指向一个存储了用户名密码的文件,格式如下:
用户名:密码
用户名2:密码2:注释
用户名3:密码3
密码必须使用函数 crypt() 加密。 我们可以使用来自 Apache 的 htpasswd 工具来创建密码文件。
3.使用方法:
server {
listen 91;
server_name localhost 127.0.0.1;
location / {
#禁用缓存
add_header Cache-Control no-cache;
auth_basic "input you username and password";
auth_basic_user_file /usr/local/nginx/conf.d/auth-conf/root-123456-conf;
alias /usr/local/nginx/html/;
index index1.html;
}
}
记得添加禁用缓存那一句,不然后面测试注销的时候会无效。
该配置表明,只要访问本机的91端口,就需要进行登录认证,可用的登录信息存储在文件/usr/local/nginx/conf.d/auth-conf/root-123456-conf
中。
[root@master02 conf.d]# cat /usr/local/nginx/conf.d/auth-conf/root-123456-conf
我这里有两组用户数据。
4.密码生成:
使用htpasswd
工具生成密码。
如果没有htpasswd
工具,可以先进行安装,安装命令:
[root@master02 auth-conf]# yum -y install htpasswd
如果这个安装不了就装下面这个
[root@master02 auth-conf]# yum install httpd-tools
密码生成命令格式:htpasswd -c 存放用户名密码的文件路径 用户名
[root@master02 auth-conf]# htpasswd -c /usr/local/nginx/conf.d/auth-conf/root-123456-conf root
然后输入两遍密码,就可以生成对应的用户名密码文件了。
之后,我们就可以尝试用浏览器访问服务器的91端口。
5.登录验证:
这样就会让我们输入用户名跟秘密。
输入正确的用户名跟密码,就可以访问对于的资源了。
如果我们想要在非浏览器中使用http命令访问该资源,则可以使用如下命令:
http://root:123456@192.168.137.252:91
命令格式:http://用户名:密码@IP地址:端口
二、注销登录
因为nginx子代的Auth_basic模块是没有退出登录功能的,只有在关闭整个浏览器之后,此次登录会话才会失效。但是我们可以做一个地址,使用错误的用户名跟密码来使之前的登录会话失效。
使用如下配置,用户访问:91/logout
的时候,将会让用户强制携带错误的用户名密码登录,此时浏览器会使之前的登录会话失效。
location /logout {
auth_basic off;
default_type text/html;
return 200 "<html><script>window.location.href='http://df32ds%w:j3js3_@$server_addr:91';</script></html>";
}
重启nginx:
[root@master02 conf.d]# /usr/local/nginx/sbin/nginx -t
[root@master02 conf.d]# /usr/local/nginx/sbin/nginx -s reload
使用浏览器验证登录与注销登录功能:
1.登录:
打开google浏览器的无痕窗口,访问http://192.168.137.252:91/
输入用户名密码之后,可以成功访问页面。
2.注销登录:
访问http://192.168.137.252:91/logout
进行注销登录
此时浏览器会直接提示输入用户名密码。
我们点击取消
。浏览器会定向到无权限页面。此时访问http://192.168.137.252:91/
就会重新提示登录了。这个方法可以达到不关闭浏览器就可以换账号登录的效果。
参考文档:http://www.nginx.cn/doc/standard/httpauthbasic.html