nginx 屏蔽ip

在网站运行过程中,我们有的时候需要对某个IP或者IP段进行封禁,禁止IP访问本服务器,如果服务器的环境用的是Nginx,下面我们来看看Nginx如何禁止某个IP访问!

方法一:
首先在nginx的conf目录下建立名为blocksip.conf配置文件:

然后用vim打开blocksip.conf文件,写入以下规则:

deny xxx.xxx.xxx.xxx; (xxx为需要封禁的IP)
保存一下。

在nginx的配置文件nginx.conf中加入:

include blocksip.conf;
重启下nginx的服务:

service nginx restart
blocksip.conf:的格式还有许多种,可以配置只允许的IP访问或者IP段访问:

deny IP;
allow IP;
# block all ips
deny all;
# allow all ips
allow all;
其中网段的写法是这样的:192.168.1.0/24这样的形式。

deny 192.168.1.11;
deny 192.168.1.123;
deny 10.0.1.0/24;
如果你想实现这样的应用,除了几个IP外,其他全部拒绝,

那需要你在ip.balcklist中这样写

allow 1.1.1.1;
allow 1.1.1.2;
deny all;
单独网站屏闭IP的方法:

在server”{}”,在这个大括号内加入deny IP地址是限制某IP地址访问;allow IP地址是只允许某IP地址访问;

屏蔽单个IP的命令是

deny 123.45.6.7

封整个段即从123.0.0.1到123.255.255.254的命令

deny 123.0.0.0/8

封IP段即从123.45.0.1到123.45.255.254的命令

方法二:
使用iptables
1、iptables -L -n //查看iptables规则
2、iptables -F //清掉iptables规则
3、封闭ip命令
单个IP的命令是
iptables -I INPUT -s 124.115.0.199 -j DROP

deny 124.45.0.0/16

封IP段即从123.45.6.1到123.45.6.254的命令是

deny 123.45.6.0/24

4、 service iptables save ,保存规则,不然重启会将原来设置的规则覆盖掉
5、systemctl restart iptables //重启iptables
6、删除一条已有的规则
iptables -L INPUT –line-numbers //查看规则对应的rulenum
iptables -D chain rulenum //chain 对应的是-I 后面的命令,如上图设置为 “INPUT” ,

重启防火墙失败 ,Failed to restart iptables.service: unit not found.
解决办法:
yum install iptables-services //重新安装一遍
systemctl stop iptables && systemctl disable iptables
systemctl start iptables && systemctl enable iptables

原文地址:https://www.cnblogs.com/azhqiang/p/13970384.html