Skip to main content
Version: 3.8

ip-restriction

描述#

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

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

属性#

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

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

启用插件#

以下示例展示了如何在特定路由上启用 ip-restriction 插件,并配置 whitelist 属性:

curl http://127.0.0.1:9180/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
{
"uri": "/index.html",
"upstream": {
"type": "roundrobin",
"nodes": {
"127.0.0.1:1980": 1
}
},
"plugins": {
"ip-restriction": {
"whitelist": [
"127.0.0.1",
"113.74.26.106/24"
]
}
}
}'

当使用白名单之外的 IP 访问时,默认返回 {"message":"Your IP address is not allowed"}。如果想使用自定义的 message,可以在插件配置中进行调整:

"plugins": {
"ip-restriction": {
"whitelist": [
"127.0.0.1",
"113.74.26.106/24"
],
"message": "Do you want to do something bad?"
}
}

测试插件#

启用插件后,使用 curl 命令访问 APISIX 实例地址:

curl http://127.0.0.1:9080/index.html -i

返回 200 HTTP 状态码,代表访问成功:

HTTP/1.1 200 OK
...

再从 IP 地址 127.0.0.2 发出请求:

curl http://127.0.0.1:9080/index.html -i --interface 127.0.0.2

返回 403 HTTP 状态码,代表访问被阻止:

HTTP/1.1 403 Forbidden
...
{"message":"Your IP address is not allowed"}

如果你需要更改白名单或黑名单的 IP 地址,你只需更新插件配置,无需重启服务:

curl http://127.0.0.1:9180/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
{
"uri": "/index.html",
"upstream": {
"type": "roundrobin",
"nodes": {
"127.0.0.1:1980": 1
}
},
"plugins": {
"ip-restriction": {
"whitelist": [
"127.0.0.2",
"113.74.26.106/24"
]
}
}
}'

删除插件#

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

curl http://127.0.0.1:9180/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
{
"uri": "/index.html",
"plugins": {},
"upstream": {
"type": "roundrobin",
"nodes": {
"127.0.0.1:1980": 1
}
}
}'