访问控制

http_access_module

基于IP的访问控制

# 允许哪些 ip(address)、网段(CIDR)、socket方式(unix:)、所有(all) 可以访问
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

示例:

#限制我的ip不可访问,其他所有的都可以访问
#被限制的ip会显示 403 Forbidden
location ! ^/admin.html {
    root /usr/share/nginx/html;
    deny 140.207.236.xxx;
    allow all;
}

#只允许以下网段访问,其他一概不允许访问
location ! ^/admin.html {
    root /usr/share/nginx/html;
    allow 182.168.173.0/24;
    deny all;
}

局限性

如果客户端经过代理访问nginx服务端,如下图:

因为access_module是根据 $remote_addr来进行限制的,那么对于Nginx来说,此时$remote_addr就是IP2,那么nginx对IP1的限制就失效了。这就是局限性。

针对这种问题共有以下几种方式:

  • http_x_forwarded_for

  • 结合geo模块

  • 通过HTTP自定义变量传递

http_x_forwarded_for

x_forwoared_for 会带着真正的客户端的ip(即图中的IP1)给nginx。

http_x_forwarded_for = ClientIP,Proxy1_IP,Proxy2_IP ...
# x_forwarded_for不仅包含ClientIP,还包含中间的代理ip

缺点:

  • http_x_forwarded_for 是基于协议的,不一定所有的厂商都支持,而且又被修改的可能性

http_auth_basic_module

基于用户的信任登录进行访问控制

# 开启认证,string代表开启,off代表关闭,string可以是任意值,一般是提示语
Syntax: auth_basic string|off;
Default: auth_basic off;
Context: http, server, location, limit_except

# 使用文件认证用户名密码
Syntax: auth_basic_user-file file;
Default: 
Context: http, server, location, limit_except

示例:

# 生成密码文件
# htpasswd -c /etc/nginx/auth_conf 用户名
# 期间需要手动输入面膜
htpasswd -c /etc/nginx/auth_conf admin
New password: 
Re-type new password: 
Adding password for user admin

# 查看文件
[root@localhost html]# cat /etc/nginx/auth_conf 
admin:$apr1$Kjg/tGgG$US4oklegzqMq7QITWoaj/0

# 配置nginx配置
location ~ ^/admin.html {
	root /usr/share/nginx/html;
	auth_basic "Please input your password!";
	auth_basic_user_file /etc/nginx/auth_conf;
}

配置成功后,访问 ip:port/admin.html,会弹出如下认证提示:

局限性

  • 用户信息需要存储在文件中,依赖文件

  • 操作机械、管理低效

对应的解决方案:

  • nginx结合LUA实现高效验证

  • nginx配合LDAP打通,利用nginx-auth-ldap模块

最后更新于