插件窝 干货文章 Nginx访问限制怎么配置

Nginx访问限制怎么配置

限制 Nginx location 请求 676    来源:    2025-04-26

Nginx访问限制配置指南

Nginx提供了多种方式来限制访问,包括基于IP的限制、连接数限制和请求速率限制等。以下是几种常见的访问限制配置方法:

1. 基于IP的访问限制

限制特定IP访问

location /admin/ {
    allow 192.168.1.100;  # 允许的IP
    allow 10.0.0.0/24;    # 允许的IP段
    deny all;             # 拒绝其他所有IP
}

黑名单方式

location / {
    deny 192.168.1.1;     # 拒绝特定IP
    deny 123.45.67.89;    # 拒绝另一个IP
    allow all;            # 允许其他所有IP
}

2. 请求速率限制

限制请求速率

http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

    server {
        location /search/ {
            limit_req zone=one burst=5;
        }
    }
}
  • 10m:共享内存区域大小
  • rate=1r/s:每秒1个请求
  • burst=5:允许突发5个请求

限制并发连接数

http {
    limit_conn_zone $binary_remote_addr zone=addr:10m;

    server {
        location /download/ {
            limit_conn addr 1;  # 每个IP最多1个连接
        }
    }
}

3. 基于用户认证的限制

基本HTTP认证

location /private/ {
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

需要创建.htpasswd文件:

htpasswd -c /etc/nginx/.htpasswd username

4. 地理位置限制

需要安装ngx_http_geoip_module模块:

http {
    geoip_country /usr/share/GeoIP/GeoIP.dat;

    map $geoip_country_code $allowed_country {
        default no;
        US yes;
        CA yes;
        GB yes;
    }

    server {
        if ($allowed_country = no) {
            return 403;
        }
    }
}

5. 限制特定HTTP方法

location /api/ {
    if ($request_method !~ ^(GET|POST)$ ) {
        return 405;
    }
}

6. 限制User-Agent

location / {
    if ($http_user_agent ~* (wget|curl|libwww-perl)) {
        return 403;
    }
}

最佳实践提示

  1. 对于生产环境,建议先测试限制规则
  2. 可以使用limit_req_statuslimit_conn_status自定义返回状态码
  3. 对于API接口,考虑结合令牌桶算法进行更精细的限流
  4. 监控受限IP的日志,调整限制策略

配置完成后,记得测试并重新加载Nginx配置:

nginx -t && nginx -s reload