文章目录
- 基于IP的访问控制
http_access_module
- 基于用户登陆认证
http_auth_basic_module
基于IP的访问控制http_access_module
参考文档:http://nginx.org/en/docs/http/ngx_http_access_module.html
- 允许配置语法
Syntax: allow address | CIDR | unix: | all;
Default: —
Context: http, server, location, limit_except
- 拒绝配置语法
Syntax: deny address | CIDR | unix: | all;
Default: —
Context: http, server, location, limit_except
示例一:拒绝192.168.1.4访问,允许其他所有主机访问
#拒绝访问配置
location ~ ^/1.html {
deny 192.168.1.4;
allow all;
}
示例二:只允许192.168.1.4访问,不允许其他
#拒绝访问配置
location ~ ^/1.html {
allow 192.168.1.4;
deny all;
}
//注意先允许后拒绝,位置写反了达不到效果
示例三:只允许本机访问状态监控/mystatus
location /mystatus {
stub_status on;
allow 127.0.0.1;
deny all;
}
效果:192.168.1.4访问192.168.1.17
[root@rhel ~]# curl 192.168.1.17/
aaaaa
[root@rhel ~]# curl 192.168.1.17/mystatus
<html>
<head><title>403 Forbidden</title></head>
<body bgcolor="white">
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.14.1</center>
</body>
</html>
[root@rhel ~]#
# 自己就可以访问状态监控
[root@mysql-slave ~]$ curl 127.0.0.1/mystatus
Active connections: 1
server accepts handled requests
30 30 42
Reading: 0 Writing: 1 Waiting: 0
[root@mysql-slave ~]$
http_access_module
的局限性
- 若使用
http_x_forwarded_for
记录真实客户端IP地址以及代理服务器IP
- 解决方式:
- 采用http头信息控制访问,代理及web服务器开启
http_x_forworded_for
,(要大家都遵循开启) - 结合geo模块
- 通过HTTP自动以变量方式传递
基于用户登陆认证http_auth_basic_module
参考文档:http://nginx.org/en/docs/http/ngx_http_auth_basic_module.html
- 配置语法:
Syntax: auth_basic string | off;
Default: auth_basic off; #默认是关闭的
Context: http, server, location, limit_except
- 协议启用用户名和密码验证。指定的参数用作
realm
,特殊值off允许取消auth_basic从先前配置级别继承的指令的效果
Syntax: auth_basic_user_file file;
Default: —
Context: http, server, location, limit_except
# 指定保存用户名和密码的文件,格式如下
name1:password1
name2:password2:comment
name3:password3
示例:只有用户lss和admin能通密码访问下载站点
# 需要先按装依赖组件生成账户密码:yum install -y httpd-tools
[root@mysql-slave ~]$ htpasswd -c /etc/nginx/auth_conf lss
New password:
Re-type new password:
Adding password for user lss
[root@mysql-slave ~]$ cat /etc/nginx/auth_conf
lss:$apr1$E/BT5LqC$7I0thvfHLxITHGZPTyzj70
# 新增用户
[root@mysql-slave ~]$ htpasswd -b /etc/nginx/auth_conf admin 123123
Adding password for user admin
[root@mysql-slave ~]$ cat /etc/nginx/auth_conf
lss:$apr1$E/BT5LqC$7I0thvfHLxITHGZPTyzj70
admin:$apr1$EJQbPeri$Vr/X.yk2YOEHkUPxp0V8Z1
[root@mysql-slave ~]$
[root@mysql-slave /etc/nginx]$ vim nginx.conf
...
location /download {
alias /soft/scripts;
autoindex on;
autoindex_localtime on;
autoindex_exact_size off;
charset utf-8,gbk;
limit_rate_after 10m;
limit_rate 128;
auth_basic "请输入账号密码!";
auth_basic_user_file /etc/nginx/auth_conf;
}
http_auth_basic_module
局限性
- 用户信息依赖文件方式,管理操作机械,效率不高
解决方法:
- Nginx结合LUA实现高效验证
- Nginx结合LDAP,利用
nginx_auth_ldap
模块