Skip to content

PrefixPath GatewayFilter 工厂

PrefixPath GatewayFilter 工厂接受一个 prefix(前缀)参数。

以下示例配置了一个 PrefixPath GatewayFilter:

application.yml

yaml
spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - PrefixPath=/mypath

作用: 此配置会将 /mypath 作为前缀添加到所有匹配请求的路径前面。 因此,发送到 /hello 的请求会被转发到下游的 /mypath/hello

补充教学 —— 为什么要用 PrefixPath?

场景举例:API 版本控制或服务隔离

  • 后端现状:你的用户服务提供了一个接口 /users
  • 网关需求:你希望对外暴露的 API 都带有统一的前缀,比如 /api/v1,或者为了区分服务,希望加上 /service-user
  • 问题:如果不做处理,用户访问 /service-user/users,网关转发给后端也是 /service-user/users,但后端只有 /users,会报 404。
    • 注:这种场景通常用 StripPrefix(去掉前缀),但 PrefixPath 是反过来的。

PrefixPath 的真正场景

  • 后端现状:后端应用部署在上下文路径 /app 下(即所有接口都以 /app 开头,如 /app/hello)。
  • 网关需求:为了简便,网关希望对外暴露的路径是短的 /hello
  • 解决方案:使用 PrefixPath=/app
    • 客户端请求:GET /hello
    • 网关处理:自动加上前缀,变成 /app/hello
    • 发送给后端:GET /app/hello(后端成功识别)

它相当于给请求“穿上了一件外套”,让它能匹配后端深藏的路径结构。


Based on Spring Framework.