本文将借助nginx实现对ip和ip段的封禁,接着直接切入主题,我们将借助nginx的 ngx_http_access_module 模块,它可以用来封配置内的ip或者ip段。语法如下
deny IP;
deny subnet;
allow IP;
allow subnet;
# block all ips
deny all;
# allow all ips
allow all;
如果有多条规则引起冲突,会以最前面的匹配规则为准。、
配置禁用ip和ip段
nginx我安装在/usr/local/nginx目录,在目录下面创建一个用来配置封ip的配置文件blockips.conf,然后配置需要封的ip地址
deny 1.2.3.4;
deny 91.212.45.0/24;
deny 91.212.65.0/24;
接着在nginx.conf的http配置节点添加下面一行配置
include blockips.conf;
测试一下当前的nginx配置文件是否合法
/usr/local/nginx/sbin/nginx -t
如果配置是正常的就会输出
the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
configuration file /usr/local/nginx/conf/nginx.conf test is successful
如果配置有问题根据提示去调整配置,接着让nginx重新加载配置文件
/usr/local/nginx/sbin/nginx -s reload
仅允许内网ip
我们如何只允许内网ip,禁止所有的外网ip,按照如下配置即可
location / {
# block one workstation
deny 192.168.1.1;
# allow anyone in 192.168.1.0/24
allow 192.168.1.0/24;
# drop rest of the world
deny all;
}
该配置禁止了192.168.1.1,允许其余内网网段,然后deny all禁止其它所有ip。
格式化nginx403的页面
nginx的静态页面一般放在html目录下面,然后可以自定义一个error403.html页面,页面代码
<html>
<head><title>Error 403 - IP Address Blocked</title></head>
<body>
Your IP Address is blocked. If you this an error, please contact binghe with your IP at test@binghe.com
</body>
</html>
如果我们启用SSI机制,我们在403中可以显示被封的客户端ip
Your IP Address is <!--#echo var="REMOTE\_ADDR" --> blocked.
接着再nginx配置文件,然后在server配置节点配置如下信息
error_page 403 /error403.html;
location = /error403.html {
root html;
}
然后使用nginx -t命令检查配置文件是否正确,接着nginx -s reload重新加载配置。