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 访问的情况下返回的信息。
ip-restriction - 图1note

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

启用插件

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

  1. curl http://127.0.0.1:9180/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  2. {
  3. "uri": "/index.html",
  4. "upstream": {
  5. "type": "roundrobin",
  6. "nodes": {
  7. "127.0.0.1:1980": 1
  8. }
  9. },
  10. "plugins": {
  11. "ip-restriction": {
  12. "whitelist": [
  13. "127.0.0.1",
  14. "113.74.26.106/24"
  15. ]
  16. }
  17. }
  18. }'

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

  1. "plugins": {
  2. "ip-restriction": {
  3. "whitelist": [
  4. "127.0.0.1",
  5. "113.74.26.106/24"
  6. ],
  7. "message": "Do you want to do something bad?"
  8. }
  9. }

测试插件

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

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

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

  1. HTTP/1.1 200 OK
  2. ...

再从 IP 地址 127.0.0.2 发出请求:

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

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

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

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

  1. curl http://127.0.0.1:9180/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  2. {
  3. "uri": "/index.html",
  4. "upstream": {
  5. "type": "roundrobin",
  6. "nodes": {
  7. "127.0.0.1:1980": 1
  8. }
  9. },
  10. "plugins": {
  11. "ip-restriction": {
  12. "whitelist": [
  13. "127.0.0.2",
  14. "113.74.26.106/24"
  15. ]
  16. }
  17. }
  18. }'

禁用插件

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

  1. curl http://127.0.0.1:9180/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  2. {
  3. "uri": "/index.html",
  4. "plugins": {},
  5. "upstream": {
  6. "type": "roundrobin",
  7. "nodes": {
  8. "127.0.0.1:1980": 1
  9. }
  10. }
  11. }'