ip-restriction

Description

The ip-restriction Plugin allows you to restrict access to a Service or a Route by either whitelisting or blacklisting IP addresses.

Single IPs, multiple IPs or even IP ranges in CIDR notation like 10.10.10.0/24 can be used.

Attributes

NameTypeRequiredDefaultValid valuesDescription
whitelistarray[string]FalseList of IPs or CIDR ranges to whitelist.
blacklistarray[string]FalseList of IPs or CIDR ranges to blacklist.
messagestringFalseYour IP address is not allowed.[1, 1024]Message returned when the IP address is not allowed access.
ip-restriction - 图1note

Either one of whitelist or blacklist attribute must be specified. They cannot be used together.

Enabling the Plugin

You can enable the Plugin on a Route or a Service as shown below:

  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. }'

To return a custom message when an IP address is not allowed access, configure it in the Plugin as shown below:

  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. }

Example usage

After you have configured the Plugin as shown above, when you make a request from the IP 127.0.0.1:

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

But if you make requests from 127.0.0.2:

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

To change the whitelisted/blacklisted IPs, you can update the Plugin configuration. The changes are hot reloaded and there is no need to restart the service.

  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.2",
  14. "113.74.26.106/24"
  15. ]
  16. }
  17. }
  18. }'

Disable Plugin

To disable the ip-restriction Plugin, you can delete the corresponding JSON configuration from the Plugin configuration. APISIX will automatically reload and you do not have to restart for this to take effect.

  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. }'