经过一些研究,请在下面找到适合我的方法。两种方法都产生相同的结果。
这是我的设置:
http://localhost:8090
/context
my-resources
http://localhost:8091/my-resources
/my-resources
RID
配置网关,以便传输所有路径变量(可能没有) http://localhost:8090/context/my-resources/ 被转发给uri http://localhost:8091/my-resources/ 。
http://localhost:8090/context/my-resources/
http://localhost:8091/my-resources/
application.yml
spring: cloud: gateway: routes: - id: route_id predicates: - Path=/context/my-resources/** filters: - RewritePath=/context/my-resources/(?<RID>.*), /my-resources/$\{RID} uri: http://localhost:8091
@Bean public RouteLocator routes(RouteLocatorBuilder routeBuilder) { return routeBuilder.routes() .route("route_id", route -> route .path("/context/my-resources/**") .filters(f -> f.rewritePath("/context/my-resources/(?<RID>.*)", "/my-resources/${RID}")) .uri("http://localhost:8091") ) .build(); }
一个 rewritePath 必须使用过滤器:
rewritePath
@Bean public RouteLocator routes(RouteLocatorBuilder builder) { return builder.routes() .route("users", t -> t.path("/users") .uri("http://localhost:8080/users")) .route("userById", t -> t.path("/users/**") .filters(rw -> rw.rewritePath("/users/(?<segment>.*)", "/users/${segment}")) .uri("http://localhost:8080/users/")) .build(); }
YAML版本在。中指定 文件 :
spring: cloud: gateway: routes: - id: rewritepath_route uri: http://example.org predicates: - Path=/foo/** filters: - RewritePath=/foo/(?<segment>.*), /$\{segment}