You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kong API网关db-less模式下如何配置动态端点请求路由

Kong 动态路径路由配置方案

问题根因

你当前配置存在两个核心问题:

  1. 上游路径拼写错误:Django服务的动态接口路径是复数形式/codes/<str:code>,你在Kong Service配置中写的是单数/code/,路径不匹配
  2. 正则匹配逻辑错误:你将动态数字参数部分直接写在路由路径的捕获组中,开启strip_path: true时,Kong会将整个正则匹配到的完整路径(即/alpha/code/123全部内容)剥离,导致动态参数无法被拼接到上游请求路径中,最终转发到上游的路径缺失参数部分,触发Django的404

正确配置(无需额外插件)

利用正则零宽度正向预查实现参数格式校验,同时不将参数部分纳入路径剥离范围,完整kong.yaml配置如下:

services:
  - name: local-alpha-health
    url: http://host.docker.internal:9000/health
    routes:
      - name: local-alpha-health
        methods:
          - GET
        paths:
          - /alpha/health
        strip_path: true
  - name: local-alpha-code
    url: http://host.docker.internal:9000/codes/
    routes:
      - name: local-alpha-code
        methods:
          - GET
        paths:
          - /alpha/code/(?=\d+)
        strip_path: true

配置逻辑说明

  • 修正了Service的上游路径为/codes/,和Django接口路径保持一致
  • 路由路径使用/alpha/code/(?=\d+)正则:(?=\d+)是零宽度正向预查,仅校验/alpha/code/后面必须跟随1位及以上数字才会匹配路由,不会占用实际匹配的字符长度
  • 开启strip_path: true时,Kong仅会剥离固定前缀/alpha/code/,后面的数字参数部分会被保留,自动拼接到上游Service路径末尾,最终请求/alpha/code/123会被转发到http://host.docker.internal:9000/codes/123,完全符合预期
  • 非数字路径(如/alpha/code/abc)无法通过正则预查校验,会直接返回Kong的路由不匹配提示,满足路径规则管控需求

验证结果

  • 请求GET http://127.0.0.1/alpha/health:返回{"health": "OK"},状态码200
  • 请求GET http://127.0.0.1/alpha/code/123:正常转发到对应Django接口,状态码200
  • 请求GET http://127.0.0.1/alpha/code/abc:返回{"message": "no Route matched with those values"},路由拦截生效

内容的提问来源于stack exchange,提问作者Amin Ba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 20:27:16