跳到主要内容

RewritePath 过滤器

DeepSeek V3 中英对照 RewritePath Filter RewritePath Filter

RewritePath 过滤器接收一个路径 regexp 参数和一个 replacement 参数。它使用 Java 正则表达式来灵活地重写请求路径。以下代码清单配置了一个 RewritePath 过滤器:

spring:
cloud:
gateway:
mvc:
routes:
- id: rewritepath_route
uri: https://example.org
predicates:
- Path=/red/**
filters:
- RewritePath=/red/?(?<segment>.*), /${segment}
yaml
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.rewritePath;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;

@Configuration
class RouteConfiguration {

@Bean
public RouterFunction<ServerResponse> gatewayRouterFunctionsRewritePath() {
return route("rewritepath_route")
.GET("/red/**", http("https://example.org"))
.before(rewritePath("/red/(?<segment>.*)", "/${segment}"))
.build();
}
}
java

对于请求路径 /red/blue,这会在发起下游请求之前将路径设置为 /blue。请注意,在 application.yml 中,由于 YAML 规范的要求,$ 应替换为 $\