最新の安定バージョンについては、Spring Cloud Gateway 5.0.1 を使用してください!

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 に設定されます。YAML 仕様のため、application.yml では $ を $\ に置き換える必要があることに注意してください。

lb() フィルターを使用する場合は、rewritePath() フィルターの後に配置する必要があります。そうしないと、結果の URL が不正確になる可能性があります。構成内の lb: スキームハンドラーは、フィルターを最も高い優先順位に自動的に配置します。