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

Spring Cloud Gateway本地转发路由RewritePath过滤器失效问题

解决Spring Cloud Gateway本地转发时路径重写失效及递归调用问题

问题原因

使用forward本地转发时,重写后的路径仍匹配网关路由的Path=/local/**断言,导致请求被网关反复拦截处理,引发StackOverflow异常;而HTTP远程转发时不会触发内部路由递归,因此RewritePath过滤器可正常工作。

解决方案

方案1:调整Controller路径避免递归(推荐)

将RestController的映射路径改为非/local前缀,让转发后的路径不触发网关路由:

修改Controller代码:

@GetMapping(value="/token", produces = MediaType.APPLICATION_JSON_VALUE)
public Mono<ResponseEntity<String>> createToken() {
   // 生成并返回JSON格式token的代码
}

更新网关路由配置:

spring:
  cloud:
    gateway:
      routes:
        - id: LocalRoute
          predicates:
            - Path=/local/**
          uri: forward:/
          filters:
            - RewritePath=/local/(?<segment>.*), /token/${segment}

此时请求http://example.com:8080/local/token会被重写为/token,直接匹配Controller接口,且不会再次触发网关路由。

方案2:保留原Controller路径,添加请求标记避免递归

通过添加自定义请求头,让网关仅处理未被转发过的请求:

更新网关路由配置:

spring:
  cloud:
    gateway:
      routes:
        - id: LocalRoute
          predicates:
            - Path=/local/**
            - Header=!X-Gateway-Forwarded
          uri: forward:/local
          filters:
            - RewritePath=/local/(?<segment>.*), /token/${segment}
            - AddRequestHeader=X-Gateway-Forwarded, true

原理:首次请求无X-Gateway-Forwarded头,被网关处理并添加该头;转发后的请求带有该头,会被Header=!X-Gateway-Forwarded断言排除,不再触发网关路由,直接匹配原/local/token接口。

方案3:直接指定转发目标路径(适用于固定路径场景)

如果仅需处理/local/token这一个固定路径,可简化配置(需配合方案2的请求标记逻辑避免递归):

spring:
  cloud:
    gateway:
      routes:
        - id: LocalRoute
          predicates:
            - Path=/local/token
            - Header=!X-Gateway-Forwarded
          uri: forward:/local/token
          filters:
            - AddRequestHeader=X-Gateway-Forwarded, true

内容的提问来源于stack exchange,提问作者Deepak Chhetri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 18:12:44