# 《Nginx核心技术》第05章:封禁IP和IP段

作者:冰河
星球:http://m6z.cn/6aeFbs (opens new window)
博客:https://binghe.gitcode.host (opens new window)
文章汇总:https://binghe.gitcode.host/md/all/all.html (opens new window)
星球项目地址:https://binghe.gitcode.host/md/zsxq/introduce.html (opens new window)

沉淀,成长,突破,帮助他人,成就自我。

  • 本章难度:★★☆☆☆
  • 本章重点:用最简短的篇幅介绍Nginx最核心的知识,掌握Nginx如何封禁IP和IP段,并能够灵活运用到实际项目中,维护高可用系统。

大家好,我是CurleyG~~

今天给大家介绍《Nginx核心技术》的第05章:封禁IP和IP段,多一句没有,少一句不行,用最简短的篇幅讲述Nginx最核心的知识,好了,开始今天的内容。

# 5.1 本章概述

Nginx不仅仅只是一款反向代理和负载均衡服务器,它还能提供很多强大的功能,例如:限流、缓存、黑白名单和灰度发布等等。在之前的文章中,我们已经介绍了Nginx提供的这些功能。小伙伴们可以到【Nginx专题】进行查阅。今天,我们来介绍Nginx另一个强大的功能:禁用IP和IP段。

# 5.2 禁用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;
1
2
3
4
5
6
7
8

如果规则之间有冲突,会以最前面匹配的规则为准。

# 5.3 配置禁用ip和ip段

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

首先要建一个封ip的配置文件blockips.conf,然后vi blockips.conf编辑此文件,在文件中输入要封的ip。

deny 1.2.3.4;
deny 91.212.45.0/24;
deny 91.212.65.0/24;
1
2
3

然后保存此文件,并且打开nginx.conf文件,在http配置节内添加下面一行配置:

include blockips.conf;
1

保存nginx.conf文件,然后测试现在的nginx配置文件是否是合法的:

/usr/local/nginx/sbin/nginx -t
1

如果配置没有问题,就会输出:

the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
configuration file /usr/local/nginx/conf/nginx.conf test is successful
1
2

如果配置有问题就需要检查下哪儿有语法问题,如果没有问题,需要执行下面命令,让nginx重新载入配置文件。

/usr/local/nginx/sbin/nginx -s reload
1

# 5.4 仅允许内网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;
}
1
2
3
4
5
6
7
8

上面配置中禁止了192.168.1.1,允许其他内网网段,然后deny all禁止其他所有ip。

# 5.5 格式化nginx的403页面

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

首先执行下面的命令:

cd /usr/local/nginx/html
vi error403.html
1
2

然后输入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>
1
2
3
4
5
6

如果启用了SSI,可以在403中显示被封的客户端ip,如下:

Your IP Address is <!--#echo var="REMOTE_ADDR" --> blocked.
1

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

# redirect server error pages to the static page
 error_page   403  /error403.html;
 location = /error403.html {
         root   html;
 }
1
2
3
4
5

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

好了,相信各位小伙伴们对如何通过Nginx封禁IP和IP端,有了进一步的了解,我是冰河,我们下期见~~