【Nginx】如何封禁IP和IP段?看完这篇我会了!!

写在前面

Nginx不单单只是一款反向代理和负载均衡服务器,它还能提供不少强大的功能,例如:限流、缓存、黑白名单和灰度发布等等。在以前的文章中,咱们已经介绍了Nginx提供的这些功能。今天,咱们来介绍Nginx另外一个强大的功能:禁用IP和IP段。html

禁用IP和IP段

Nginx的ngx_http_access_module 模块能够封配置内的ip或者ip段,语法以下:nginx

deny IP; 
deny subnet; 
allow IP; 
allow subnet; 
# block all ips 
deny    all; 
# allow all ips 
allow    all; 
复制代码

若是规则之间有冲突,会以最前面匹配的规则为准。缓存

配置禁用ip和ip段

下面说明假定nginx的目录在/usr/local/nginx/。bash

首先要建一个封ip的配置文件blockips.conf,而后vi 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.conf文件,而后测试如今的nginx配置文件是不是合法的:测试

/usr/local/nginx/sbin/nginx -tui

若是配置没有问题,就会输出:this

the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok 
configuration file /usr/local/nginx/conf/nginx.conf test is successful 
复制代码

若是配置有问题就须要检查下哪儿有语法问题,若是没有问题,须要执行下面命令,让nginx从新载入配置文件。spa

/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。

格式化nginx的403页面

如何格式化nginx的403页面呢?

首先执行下面的命令:

cd /usr/local/nginx/html 
vi error403.html 
复制代码

而后输入403的文件内容,例如:

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

保存error403文件,而后打开nginx的配置文件vi nginx.conf,在server配置节内添加下面内容。

# redirect server error pages to the static page 
 error_page   403  /error403.html; 
 location = /error403.html { 
         root   html; 
 } 
复制代码

而后保存配置文件,经过nginx -t命令测试配置文件是否正确,若正确经过nginx -s reload载入配置。

相关文章
相关标签/搜索