ip-restriction

描述

ip-restriction 可以通过以下方式限制对服务或路线的访问,将 IP 地址列入白名单或黑名单。 单个 IP 地址,多个 IP 地址 或 CIDR 范围,可以使用类似 10.10.10.0/24 的 CIDR 表示法。

属性

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

只能单独启用白名单或黑名单,两个不能一起使用。 message 可以由用户自定义。

如何启用

下面是一个示例,在指定的 route 上开启了 ip-restriction 插件:

  1. curl http://127.0.0.1:9080/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. }

测试插件

通过 127.0.0.1 访问:

  1. $ curl http://127.0.0.1:9080/index.html -i
  2. HTTP/1.1 200 OK
  3. ...

通过 127.0.0.2 访问:

  1. $ curl http://127.0.0.1:9080/index.html -i --interface 127.0.0.2
  2. HTTP/1.1 403 Forbidden
  3. ...
  4. {"message":"Your IP address is not allowed"}

禁用插件

当你想去掉 ip-restriction 插件的时候,很简单,在插件的配置中把对应的 json 配置删除即可,无须重启服务,即刻生效:

  1. $ curl http://127.0.0.1:9080/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. }'

现在就已移除 ip-restriction 插件,其它插件的开启和移除也类似。