RewritePath Filter

The RewritePath filter takes a path regexp parameter and a replacement parameter. This uses Java regular expressions for a flexible way to rewrite the request path. The following listing configures a RewritePath filter:

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.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();
    }
}

For a request path of /red/blue, this sets the path to /blue before making the downstream request. Note that in application.yml the $ should be replaced with $\ because of the YAML specification.