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: 方案处理程序会自动将过滤器置于最高优先级。
© . This site is unofficial and not affiliated with VMware.