前言

在没有专业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错误页面了。

[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>

参考资料:

文章目录