Apache Apisix配置ip-restriction插件以限制IP地址访问

介绍

ip-restriction 插件可以通过将 IP 地址列入白名单或黑名单来限制对服务或路由的访问。

支持对单个 IP 地址、多个 IP 地址和类似 10.10.10.0/24 的 CIDR(无类别域间路由)范围的限制。

属性

参数名 类型 必选项 默认值 有效值 描述
whitelist arraystring 加入白名单的 IP 地址或 CIDR 范围。
blacklist arraystring 加入黑名单的 IP 地址或 CIDR 范围。
message string "Your IP address is not allowed" 1, 1024 在未允许的 IP 访问的情况下返回的信息。

注意:whitelistblacklist 属性无法同时在同一个服务或路由上使用,只能使用其中之一。

配置步骤

1、从config.yaml获取admin_key并存入环境变量

admin_key=$(cat config.yaml |awk -F': +' 'BEGIN{admin_key=0}

/admin_key:/{admin_key=1}

admin_key && /^ *key:/{print $NF;admin_key=0;exit;}')

2、设置白名单,只允许172.105.0.1/16和127.0.0.1本地访问http://ip:9080

curl http://127.0.0.1:9180/apisix/admin/routes/1 -H "X-API-KEY: $admin_key" -X PUT -d '

{

"uri": "/",

"upstream": {

"type": "roundrobin",

"nodes": {

"172.105.0.4:8080": 1

}

},

"plugins": {

"ip-restriction": {

"whitelist": [

"127.0.0.1",

"172.105.0.1/16"

],

"message":"Your IP address is not allowed"

}

}

}'

3、上述配置中172.105.0.4:8080是我启动的一个Tomcat服务

目前,新版本的Tomcat默认不提供webapps了,所以访问返回404。如下是Tomcat官方(https://hub.docker.com/_/tomcat)说明:

You can then go to http://localhost:8888 or http://host-ip:8888 in a browser (noting that it will return a 404 since there are no webapps loaded by default).

如果非要显示如下页面,需要手动配置:

cp -a webapps.dist/* webapps/

4、验证配置是否生效

curl -I http://localhost:9080

HTTP/1.1 200

......

在白名单意外的IP服务器上执行

curl http://192.168.xx.xxx:9080 -i

HTTP/1.1 403 Forbidden

Date: Mon, 19 May 2025 13:21:37 GMT

Content-Type: text/plain; charset=utf-8

Transfer-Encoding: chunked

Connection: keep-alive

Server: APISIX/3.12.0

{"message":"Your IP address is not allowed"}

删除插件

当你需要禁用 ip-restriction 插件时,可以通过以下命令删除相应的 JSON 配置,APISIX 将会自动重新加载相关配置,无需重启服务:

curl http://127.0.0.1:9180/apisix/admin/routes/1 -H "X-API-KEY: $admin_key" -X PUT -d '

{

"uri": "/index.html",

"plugins": {},

"upstream": {

"type": "roundrobin",

"nodes": {

"127.0.0.1:1980": 1

}

}

}'

相关推荐
共创splendid--与您携手5 小时前
AI读取前端项目生成skill.md
前端·人工智能·ai
San813_LDD6 小时前
[C语言]《Dev-C++ 报错解决手册(Day0607 精华版)》
java·前端·javascript
xiaofeichaichai12 小时前
Webpack
前端·webpack·node.js
问心无愧051312 小时前
ctf show web入门111
android·前端·笔记
唐某人丶12 小时前
模型越来越强,我们还需要 Agent 工程吗?—— 从价值重估到 Harness 实践
前端·agent·ai编程
智码看视界12 小时前
现代Web开发基础:全栈工程师的起航点
前端·后端·c5全栈
JS菌13 小时前
手写一个 AI Agent 全栈项目:从沙箱执行到子智能体的完整实现
前端·人工智能·后端
excel14 小时前
HLS TS 文件损坏的元凶:Git 提交与拉取
前端
Aphasia31114 小时前
https连接传输流程
前端·面试