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

介绍

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

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

属性

参数名 类型 必选项 默认值 有效值 描述
whitelist array[string] 加入白名单的 IP 地址或 CIDR 范围。
blacklist array[string] 加入黑名单的 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

}

}

}'

相关推荐
饮水机战神1 分钟前
震惊!多核性能反降11%?node接口压力测试出乎意料!
前端·node.js
一只叁木Meow2 分钟前
JavaScript数学库深度对比
前端
顾辰逸you4 分钟前
uniapp--咸虾米壁纸项目(一)
前端·微信小程序
方方洛18 分钟前
电子书阅读器:epub电子书文件的解析
前端·产品·电子书
idaibin19 分钟前
Rustzen Admin 前端简单权限系统设计与实现
前端·react.js
GISer_Jinger25 分钟前
Trae Solo模式生成一个旅行足迹App
前端·javascript
zhangbao90s26 分钟前
Intl API:浏览器原生国际化API入门指南
前端·javascript·html
艾小码28 分钟前
构建现代前端工程:Webpack/Vite/Rollup配置解析与最佳实践
前端·webpack·node.js
跟橙姐学代码33 分钟前
Python 集合:人生中最简单的真理,只有一次
前端·python·ipython
复苏季风34 分钟前
站在2025 年 来看,现在应该怎么入门CSS
前端·css