RewritePath 過濾器
RewritePath 過濾器接受一個路徑 regexp 引數和一個 replacement 引數。這使用 Java 正則表示式以靈活的方式重寫請求路徑。以下列表配置了一個 RewritePath 過濾器。
application.yml
spring:
cloud:
gateway:
mvc:
routes:
- id: rewritepath_route
uri: https://example.org
predicates:
- Path=/red/**
filters:
- RewritePath=/red/?(?<segment>.*), /$\{segment}
GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.rewritePath;
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri;
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())
.before(uri("https://example.org"))
.before(rewritePath("/red/(?<segment>.*)", "/${segment}"))
.build();
}
}
對於請求路徑 /red/blue,這會在進行下游請求之前將路徑設定為 /blue。請注意,在 application.yml 中,由於 YAML 規範,$ 應該替換為 $\。
如果使用 lb() 過濾器,它需要在 rewritePath() 過濾器之後,否則生成的 URL 可能會不正確。配置中的 lb: 方案處理程式會自動將過濾器置於最高優先順序。 |