Nginx封禁IP和IP段的详细指南

Nginx提供了多种方式来封禁恶意IP或IP段,以下是几种常用方法的详细说明:

图片[1]_Nginx封禁IP和IP段的详细指南_知途无界

1. 使用Nginx配置文件封禁

单个IP封禁

在Nginx配置文件中(通常在nginx.conf或站点配置文件中)添加:

http {
    # 封禁单个IP
    deny 192.168.1.100;

    # 允许其他所有IP
    allow all;

    server {
        ...
    }
}

IP段封禁

http {
    # 封禁整个C类地址段
    deny 192.168.1.0/24;

    # 封禁B类地址段
    deny 172.16.0.0/16;

    # 允许其他所有IP
    allow all;

    server {
        ...
    }
}

2. 使用location块封禁特定路径的访问

server {
    location /admin {
        deny 192.168.1.100;
        deny 10.0.0.0/8;
        allow all;

        # 其他配置...
    }
}

3. 使用include指令管理封禁列表

创建单独的封禁IP文件(如/etc/nginx/blockips.conf):

deny 192.168.1.100;
deny 192.168.1.101;
deny 192.168.2.0/24;

然后在主配置文件中包含它:

http {
    include /etc/nginx/blockips.conf;

    server {
        ...
    }
}

4. 动态封禁(结合fail2ban)

  1. 安装fail2ban:
   sudo apt-get install fail2ban  # Debian/Ubuntu
   sudo yum install fail2ban      # CentOS/RHEL
  1. 创建Nginx专用的fail2ban配置文件/etc/fail2ban/jail.local
   [nginx-http-auth]
   enabled = true
   filter = nginx-http-auth
   port    = http,https
   logpath = /var/log/nginx/error.log

   

[nginx-badbots]

enabled = true filter = nginx-badbots port = http,https logpath = /var/log/nginx/access.log maxretry = 2

  1. 重启fail2ban:
   sudo systemctl restart fail2ban

5. 使用GeoIP模块封禁地区

  1. 确保安装了GeoIP模块(通常包含在Nginx商业版或通过--with-http_geoip_module编译)
  2. 配置示例:
   http {
       geoip_country /usr/share/GeoIP/GeoIP.dat;

       map $geoip_country_code $allowed_country {
           default yes;
           CN no;  # 封禁中国IP
           RU no;  # 封禁俄罗斯IP
       }

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

6. 使用Lua脚本动态封禁(OpenResty)

如果你使用OpenResty(Nginx+Lua),可以实现更复杂的封禁逻辑:

http {
    lua_shared_dict ip_blacklist 10m;

    init_by_lua_block {
        local blacklist = ngx.shared.ip_blacklist
        blacklist:set("192.168.1.100", true)
        blacklist:set("10.0.0.0/8", true)
    }

    server {
        location / {
            access_by_lua_block {
                local blacklist = ngx.shared.ip_blacklist
                local ip = ngx.var.remote_addr

                if blacklist:get(ip) then
                    ngx.exit(403)
                end
            }
            ...
        }
    }
}

验证和测试

  1. 测试Nginx配置是否正确:
   sudo nginx -t
  1. 重新加载Nginx配置:
   sudo nginx -s reload
  1. 测试封禁是否生效:
   curl -I http://yourdomain.com
   # 或使用特定IP测试
   curl --interface 192.168.1.100 -I http://yourdomain.com

注意事项

  1. 封禁规则是有顺序的 – Nginx会按顺序匹配allowdeny指令
  2. 对于大型IP列表,考虑使用ngx_http_geo_module提高性能
  3. 封禁IP后,建议监控日志确认效果
  4. 对于DDoS攻击,仅靠Nginx封禁可能不够,应考虑结合防火墙、CDN等方案

通过以上方法,你可以灵活地封禁单个IP、IP段甚至整个地区的访问,保护你的服务器免受恶意流量的侵扰。

© 版权声明
THE END
喜欢就点个赞,支持一下吧!
点赞24 分享
评论 抢沙发
头像
欢迎您留下评论!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容