Nginx封禁IP和IP段

在没有专业WAF的情况下,我们如果想要封禁一些恶意访问的IP(段),可以使用ngx_http_access_module模块来实现。

官方对此模块的解释:

The ngx_http_access_module module allows limiting access to certain client addresses.

指令语法

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

配置
配置conf文件

location / {
    deny  192.168.1.1;
    deny  118.31.72.34;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;  # 如果最后不添加deny all,则可能会允许上面列出ip之外的其他ip均可访问,因为默认是allow all的。
}

每次都去修改conf文件着实不方便,也不太安全(手一抖玩意改错了,nginx就鸡鸡了。),我们可以把需要封禁的ip(段)单独拎出来写成一个conf文件,然后include到nginx.conf里面。

在适当的位置(我放到了/usr/local/nginx/conf/vhost下面)新建一个XXX.conf,比如blockip.conf,写入需要封禁的IP(段)并保存。

deny  192.168.1.1;
deny  118.31.72.34;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;

然后在nginx.conf中的http{}上下文中include blockips.conf;

配置保存之后,使用-t测试一下配置文件是否有误,没有问题的话就reload一下。

[root@hkcn2 conf]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@hkcn2 conf]# /usr/local/nginx/sbin/nginx -s reload

测试封禁效果

[root@iZeo6707793o09Z ~]# curl -I http://154.209.66.13/
HTTP/1.1 403 Forbidden
Server: openresty/1.15.8.3
Date: Tue, 14 Jul 2020 11:11:27 GMT
Content-Type: text/html
Content-Length: 159
Connection: keep-alive

如果封禁没有问题,则会返回403状态码。

自定义403页面
在/usr/local/nginx/html新建一个blockip403.html,适当的写一些文案。

<html>
<head><title>Error 403 - IP Address Blocked</title></head>
<body>
Your IP Address is blocked. If you this an error, please contact webmaster with your IP at webmaster@example.com
</body>
</html>

然后在配置文件中(server{}上下文中)使用上面自定义的403错误页面。

 error_page   403  /blockip403.html;
 location = /blockip403.html {
         root   html;
 }
``
保存并检查无误后,reload一下,再次访问就看到我们自定义的403错误页面了。

```bash
`[root@iZeo6707793o09Z ~]# curl http://154.209.66.13/
<html>
<head><title>Error 403 - IP Address Blocked</title></head>
<body>
Your IP Address is blocked. If you this an error, please contact webmaster with your IP at webmaster@example.com
</body>
</html>

如果你需要对整个IP段设置不允许访问,可以这么写:

deny 123.0.0.0/8;        // 封 123.0.0.1~123.255.255.254 这个段的ip
deny 123.123.0.0/16;     // 封 123.123.0.1~123.123.255.254 这个段的ip
deny 123.123.123.0/24;   // 封 123.123.123.1~123.123.123.254 这个段的ip
deny all;                // 封所有ip
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值