# URI 拦截

当请求 URI 匹配一个或多个配置的正则表达式时，`uri-blocker` 插件会拒绝请求。它可以保护内部路径、拦截不允许的查询参数，并直接返回指定的状态码和错误消息，而不访问上游服务。

## 示例[​](#examples "示例的直接链接")

第一个示例拦截内部路径并返回自定义响应。第二个示例更新同一条路由，以忽略大小写的方式拦截查询参数。

如果启用了 Admin API 身份验证，请在使用 **Admin API** 标签页前将具有管理员角色的密钥导出为 `ADMIN_API_KEY`。

### 拦截内部路径[​](#block-an-internal-path "拦截内部路径的直接链接")

为内部路径和公开的 httpbin.org 端点配置一条路由。匹配内部路径规则的请求会在访问上游之前被拒绝。

* Admin API
* ADC
* Ingress Controller

创建路由。

```
curl "http://127.0.0.1:9180/apisix/admin/routes/uri-blocker-route" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "uris": [

      "/internal/*",

      "/anything"

    ],

    "plugins": {

      "uri-blocker": {

        "block_rules": [

          "^/internal(?:/|\\?|$)"

        ],

        "rejected_code": 403,

        "rejected_msg": "internal path blocked"

      }

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org:80": 1

      }

    }

  }'
```

配置 ADC 以连接目标后端。后续 ADC 命令会从这些环境变量读取连接设置。

* APISIX
* API7 网关

如果启用了 Admin API 身份验证，请在配置 ADC 前将具有管理员角色的密钥导出为 `ADMIN_API_KEY`。

```
export ADC_BACKEND=apisix

export ADC_SERVER="http://127.0.0.1:9180"

export ADC_TOKEN="${ADMIN_API_KEY}"
```

```
export ADC_BACKEND=api7ee

export ADC_SERVER="https://{DASHBOARD_ADDR}"

export ADC_TOKEN="{DASHBOARD_TOKEN}"

export ADC_GATEWAY_GROUP="{GATEWAY_GROUP}"
```

创建服务和路由。

adc.yaml

```
services:

  - name: uri-blocker-service

    labels:

      docs-example: uri-blocker

    routes:

      - name: uri-blocker-route

        uris:

          - /internal/*

          - /anything

        plugins:

          uri-blocker:

            block_rules:

              - ^/internal(?:/|\?|$)

            rejected_code: 403

            rejected_msg: internal path blocked

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览改动，确认仅影响本示例的资源。

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=uri-blocker
```

核对 `diff.yaml`，再同步带有此标签的服务。

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=uri-blocker
```

继续之前，先在 `aic` 命名空间中[设置 Ingress Controller 和网关](https://docs.apiseven.com/ingress-controller/set-up-ingress-controller-and-gateway.md)。

为示例上游创建 ExternalName 服务：

uri-blocker-upstream.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - port: 80

      targetPort: 80
```

应用上游服务：

```
kubectl apply -f uri-blocker-upstream.yaml
```

使用部署所采用的 Kubernetes API 配置路径规则：

* Gateway API
* APISIX CRD

uri-blocker-ic.yaml

```
apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: uri-blocker-route

spec:

  plugins:

    - name: uri-blocker

      config:

        block_rules:

          - ^/internal(?:/|\?|$)

        rejected_code: 403

        rejected_msg: internal path blocked

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: uri-blocker-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: PathPrefix

            value: /internal/

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: uri-blocker-route

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

uri-blocker-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixPluginConfig

metadata:

  namespace: aic

  name: uri-blocker-route

spec:

  ingressClassName: apisix

  plugins:

    - name: uri-blocker

      enable: true

      config:

        block_rules:

          - ^/internal(?:/|\?|$)

        rejected_code: 403

        rejected_msg: internal path blocked

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: uri-blocker-route

spec:

  ingressClassName: apisix

  http:

    - name: uri-blocker-route

      match:

        paths:

          - /internal/*

          - /anything

      backends:

        - serviceName: httpbin-external-domain

          servicePort: 80

      plugin_config_name: uri-blocker-route
```

应用路由配置：

```
kubectl apply -f uri-blocker-ic.yaml
```

向被拦截的路径发送请求：

```
curl --include "http://127.0.0.1:9080/internal/report"
```

被拦截的请求返回配置的状态码和消息：

```
HTTP/1.1 403 Forbidden

...

{"error_msg":"internal path blocked"}
```

发送不匹配规则的请求：

```
curl "http://127.0.0.1:9080/anything" \

  --silent \

  --output /dev/null \

  --write-out "Allowed response: %{http_code}\n"
```

访问公开端点的请求会到达上游：

```
Allowed response: 200
```

### 忽略大小写匹配查询参数[​](#match-a-query-option-without-case-sensitivity "忽略大小写匹配查询参数的直接链接")

更新现有路由上的插件，拦截 `debug=true` 查询参数，并忽略大小写：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes/uri-blocker-route" -X PATCH \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -H "Content-Type: application/json" \

  -d '{

    "plugins": {

      "uri-blocker": {

        "block_rules": [

          "[?&]debug=true(?:&|$)"

        ],

        "rejected_code": 403,

        "rejected_msg": "debug mode blocked",

        "case_insensitive": true

      }

    }

  }'
```

在 `adc.yaml` 中替换现有路由上的插件配置：

adc.yaml (route plugin)

```
plugins:

  uri-blocker:

    block_rules:

      - '[?&]debug=true(?:&|$)'

    rejected_code: 403

    rejected_msg: debug mode blocked

    case_insensitive: true
```

预览并同步更新后的文件：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=uri-blocker



adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=uri-blocker
```

使用部署所采用的 Kubernetes API 更新现有插件配置。第一个示例中的路由和上游服务保持不变。

* Gateway API
* APISIX CRD

uri-blocker-ic.yaml

```
apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: uri-blocker-route

spec:

  plugins:

    - name: uri-blocker

      config:

        block_rules:

          - '[?&]debug=true(?:&|$)'

        rejected_code: 403

        rejected_msg: debug mode blocked

        case_insensitive: true
```

uri-blocker-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixPluginConfig

metadata:

  namespace: aic

  name: uri-blocker-route

spec:

  ingressClassName: apisix

  plugins:

    - name: uri-blocker

      enable: true

      config:

        block_rules:

          - '[?&]debug=true(?:&|$)'

        rejected_code: 403

        rejected_msg: debug mode blocked

        case_insensitive: true
```

应用更新后的插件配置：

```
kubectl apply -f uri-blocker-ic.yaml
```

发送查询参数值为大写的请求：

```
curl --include "http://127.0.0.1:9080/anything?DEBUG=TRUE"
```

忽略大小写的规则会拦截该请求：

```
HTTP/1.1 403 Forbidden

...

{"error_msg":"debug mode blocked"}
```

发送查询参数值不匹配规则的请求：

```
curl "http://127.0.0.1:9080/anything?debug=false" \

  --silent \

  --output /dev/null \

  --write-out "Allowed response: %{http_code}\n"
```

值不匹配规则的请求会到达上游：

```
Allowed response: 200
```
