StripContextPath フィルター
StripContextPath フィルターは、下流のフィルターが処理する前に、リクエスト URI からサーブレットのコンテキストパス(server.servlet.context-path で設定)を削除します。これは、StripPrefix、RewritePath、PrefixPath などのパス操作フィルターが、ルーティング述語が一致するパスと同じパスに対して、コンテキストパスのプレフィックスなしで動作する必要がある場合に役立ちます。
StripContextPath フィルターは、フィルターチェーン内のパス操作フィルターよりも前に配置する必要があります。以下のリストは、StripContextPath フィルターの設定例です。
application.yml
server:
servlet:
context-path: /context
spring:
cloud:
gateway:
server:
webmvc:
routes:
- id: strip_context_path_route
uri: https://example.org
predicates:
- Path=/name/**
filters:
- StripContextPath
- StripPrefix=1GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.stripContextPath;
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.stripPrefix;
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> gatewayRouterFunctionsStripContextPath() {
return route("strip_context_path_route")
.GET("/name/**", http())
.before(uri("https://example.org"))
.before(stripContextPath())
.before(stripPrefix(1))
.build();
}
}server.servlet.context-path=/context の場合、ゲートウェイ経由で /context/name/blue にリクエストが行われると、StripContextPath フィルターが /context プレフィックスを削除し、次に StripPrefix が /name を削除して、ダウンストリームのリクエストが example.org/blue (英語) になります。
The StripContextPath filter must be listed before StripPrefix、RewritePath、PrefixPath, or any other filter that operates on the request path. Filters execute in the order they are defined, and these filters need the context-path already removed to work correctly. |