插件窝 干货文章 Nginx如何实现基于请求来源IP的访问控制配置

Nginx如何实现基于请求来源IP的访问控制配置

使用 Nginx 配置 控制 264    来源:    2025-04-10

Nginx基于请求来源IP的访问控制配置

Nginx可以通过多种方式实现基于客户端IP地址的访问控制,以下是几种常见的方法:

1. 使用allowdeny指令

这是最基础的IP访问控制方式,可以在httpserverlocation块中使用:

location / {
    # 允许特定IP
    allow 192.168.1.1;
    allow 10.0.0.0/24;

    # 拒绝其他所有IP
    deny all;

    # 其他配置...
}

2. 使用geo模块

geo模块可以创建变量基于客户端IP地址:

http {
    # 创建$allowed变量,默认为0(拒绝),特定IP为1(允许)
    geo $allowed {
        default 0;
        192.168.1.1 1;
        10.0.0.0/24 1;
    }

    server {
        location / {
            if ($allowed = 0) {
                return 403;
            }
            # 其他配置...
        }
    }
}

3. 使用map模块

类似于geo,但更灵活:

http {
    map $remote_addr $allowed {
        default 0;
        192.168.1.1 1;
        10.0.0.0/24 1;
    }

    server {
        location / {
            if ($allowed = 0) {
                return 403;
            }
            # 其他配置...
        }
    }
}

4. 使用ngx_http_access_module模块

这是Nginx默认编译的模块,提供基本的访问控制功能:

location /admin {
    # 只允许特定IP访问/admin路径
    allow 192.168.1.100;
    allow 10.0.0.0/24;
    deny all;

    # 其他配置...
}

5. 结合X-Forwarded-For头(用于反向代理后)

当Nginx位于负载均衡器或CDN后面时:

location / {
    # 从X-Forwarded-For获取真实IP
    set $real_ip $remote_addr;
    if ($http_x_forwarded_for ~ "^(\d+\.\d+\.\d+\.\d+)") {
        set $real_ip $1;
    }

    # 基于真实IP进行控制
    if ($real_ip !~ "^(192\.168\.1\.1|10\.0\.0\.\d+)$") {
        return 403;
    }

    # 其他配置...
}

6. 使用ngx_http_geoip_module模块(需要安装)

可以基于国家/地区进行访问控制:

http {
    geoip_country /path/to/GeoIP.dat;

    server {
        location / {
            if ($geoip_country_code != US) {
                return 403;
            }
            # 其他配置...
        }
    }
}

最佳实践建议

  1. 对于简单的IP控制,使用allow/deny指令最为直接
  2. 当规则复杂时,使用geomap模块更易于维护
  3. 在反向代理环境中,确保正确处理X-Forwarded-For头
  4. 对于大量IP列表,考虑使用include文件方式管理:
# 在配置文件中
include /etc/nginx/conf.d/allowed_ips.conf;

# allowed_ips.conf内容
allow 192.168.1.1;
allow 10.0.0.0/24;
# ...
  1. 定期审查和更新IP访问规则,确保安全性

以上方法可以根据实际需求单独使用或组合使用,以实现灵活的IP访问控制策略。