Spring Cloud Gateway's built-in filter factory
Built-in filter factory
Here is a simple table of all the filter factories built into Spring Cloud Gateway.
Filter Factory | Effect | parameter |
---|---|---|
AddRequestHeader | Add a Header for the original request | Name and value of Header |
AddRequestParameter | Add request parameters to the original request | Parameter name and value |
AddResponseHeader | Add a Header for the original response | Name and value of Header |
DedupeResponseHeader | Remove duplicate values in response headers | Header Name and Reduplication Policy Required |
Hystrix | Breaker protection with Hystrix for routing | Name of HystrixCommand |
FallbackHeaders | Add specific exception information to fallbackUri's request header | Name of Header |
PrefixPath | Prefix the original request path | prefix path |
PreserveHostHeader | To add a preserveHostHeader=true property to the request, the routing filter checks the property to determine whether to send the original HostHeader | nothing |
RequestRateLimiter | Used to limit flow to requests, the current limiting algorithm is a token bucket | keyResolver,rateLimiter,statusCode,denyEmptyKey,emptyKeyStatus |
RedirectTo | Redirect the original request to the specified URL | http status code and redirected url |
RemoveHopByHopHeadersFilter | Delete a series of headers specified by the IETF organization for the original request | The default is enabled and you can configure to specify which headers are deleted only |
RemoveRequestHeader | Delete a Header for the original request | Header Name |
RemoveResponseHeader | Delete a Header for the original response | Header Name |
RewritePath | Rewrite the original request path | The original path regular expression and the rewritten path regular expression |
RewriteResponseHeader | Override a Header in the original response | Header name, regular expression of value, overridden value |
SaveSession | Enforce the WebSession::save operation before forwarding the request | nothing |
secureHeaders | Add a series of security response headers to the original response | None, supports modifying the values of these security response headers |
SetPath | Modify the original request path | Modified Path |
SetResponseHeader | Modify the value of a Header in the original response | Header name, modified value |
SetStatus | Modify the status code of the original response | HTTP status code, either a number or a string |
StripPrefix | Path used to truncate the original request | Number of paths to truncate |
Retry | Retry for different responses | retries,statuses,methods,series |
RequestSize | Sets the maximum request packet size allowed to receive. Returns 413 Payload Too Large if the request packet size exceeds the set value | Request packet size in bytes, default 5M |
ModifyRequestBody | Modify the original request body content before forwarding the request | Modified Request Body Content |
ModifyResponseBody | Modify the contents of the original response body | Modified Response Body Content |
Default | Add filters for all routes | Filter Factory Name and Value |
**Tips:**Each filter factory corresponds to an implementation class, and the names of these classes must end with a GatewayFilterFactory, which is a convention of Spring Cloud Gateway, such as AddRequestHeader whose corresponding implementation class is AddRequestHeaderGatewayFilterFactory.
1,AddRequestHeader GatewayFilter Factory
Add a Header for the original request, configuration example:
spring: cloud: gateway: routes: - id: add_request_header_route uri: https://example.org filters: - AddRequestHeader=X-Request-Foo, Bar
Add a request header named X-Request-Foo with a value of Bar to the original request
2,AddRequestParameter GatewayFilter Factory
Add request parameters and values to the original request, configuration example:
spring: cloud: gateway: routes: - id: add_request_parameter_route uri: https://example.org filters: - AddRequestParameter=foo, bar
Add a parameter named foo with a value of bar to the original request, that is, foo=bar
3,AddResponseHeader GatewayFilter Factory
Add a Header for the original response, configuration example:
spring: cloud: gateway: routes: - id: add_response_header_route uri: https://example.org filters: - AddResponseHeader=X-Response-Foo, Bar
Add a response header named X-Request-Foo with a value of Bar to the original response
4,DedupeResponseHeader GatewayFilter Factory
DedupeResponseHeader eliminates duplicate values in response headers based on the configured Header name and the de-duplication policy, a new feature offered by Spring Cloud Greenwich SR2 that is not available below this version.
We have CORS headers on both Gateway and Micro Services. If we don't configure anything, then request->gateway->Micro Services will get CORS Header values like this:
Access-Control-Allow-Credentials: true, true Access-Control-Allow-Origin: https://musk.mars, https://musk.mars
You can see that the values of both headers are duplicated. To weigh these two headers, you need to use the DedupeResponse Header, which is a configuration example:
spring: cloud: gateway: routes: - id: dedupe_response_header_route uri: https://example.org filters: # If more than one Header needs to be weighted, use space to separate - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
Reduplication strategy:
- RETAIN_FIRST: Default, keep first value
- RETAIN_LAST: Keep the last value
- RETAIN_UNIQUE: Keep all unique values in the order they first appear
For a more complete understanding of the filter factory, it is recommended that you read the source code for the filter factory as it contains detailed comments and examples that are better than the official documentation: org.springframework.cloud.gateway.filter.factory.DedupeResponseHeaderGatewayFilterFactory
5,Hystrix GatewayFilter Factory
To introduce Hystrix breaker protection for routing, configure an example:
spring: cloud: gateway: routes: - id: hystrix_route uri: https://example.org filters: - Hystrix=myCommandName
Hystrix is the first generation of Fault Tolerant components of Spring Cloud, but it has entered maintenance mode. Hystrix will be removed by Spring Cloud in the future and replaced by Alibaba Sentinel/Resilience 4J. So this is not covered in detail and you can refer to the official documentation if you are interested:
6,FallbackHeaders GatewayFilter Factory
Also supported for Hystrix, the filter factory described in the previous section supports a configuration parameter: fallbackUri, which forwards requests to a specific URI when an exception occurs. FallbackHeaders, a filter factory, can add a Header when forwarding requests to that uri, whose value is specific exception information.
spring: cloud: gateway: routes: - id: ingredients uri: lb://ingredients predicates: - Path=//ingredients/** filters: - name: Hystrix args: name: fetchIngredients fallbackUri: forward:/fallback - id: ingredients-fallback uri: http://localhost:9994 predicates: - Path=/fallback filters: - name: FallbackHeaders args: executionExceptionTypeHeaderName: Test-Header
There are no detailed descriptions here. Interested people can refer to the official documents:
7,PrefixPath GatewayFilter Factory
Add a prefix path to the original request path, configuration example:
spring: cloud: gateway: routes: - id: prefixpath_route uri: https://example.org filters: - PrefixPath=/mypath
This configuration allows access to ${GATEWAY_URL}/hello to be forwarded tohttps://example.org/mypath/hello
8,PreserveHostHeader GatewayFilter Factory
To request the addition of a preserveHostHeader=true property, the routing filter checks the property to determine whether to send the original HostHeader.Configuration example:
spring: cloud: gateway: routes: - id: preserve_host_route uri: https://example.org filters: - PreserveHostHeader
If not set, the Header named Host will be controlled by the Http Client
9,RequestRateLimiter GatewayFilter Factory
Used to limit the flow of a request, the current limiting algorithm is a token bucket. Configuration example:
spring: cloud: gateway: routes: - id: requestratelimiter_route uri: https://example.org filters: - name: RequestRateLimiter args: redis-rate-limiter.replenishRate: 10 redis-rate-limiter.burstCapacity: 20
Since another article has already described how to use this filter factory to achieve gateway throttling, it will not be repeated here:
Or refer to the official documentation:
10,RedirectTo GatewayFilter Factory
Redirect the original request to the specified Url, configuration example:
spring: cloud: gateway: routes: - id: redirect_route uri: https://example.org filters: - RedirectTo=302, https://acme.org
This configuration redirects access to ${GATEWAY_URL}/hello to https://acme.org/hello And carry a Location:http://acme.org Header, while HTTP status code returned to client is 302
Matters needing attention:
- The HTTP status code should be 3xx, for example 301
- The URL must be a valid URL that will be used as the value of the Location Header
11,RemoveHopByHopHeadersFilter GatewayFilter Factory
Delete for original request IETF A series of headers defined by the organization, which are deleted by default, are as follows:
- Connection
- Keep-Alive
- Proxy-Authenticate
- Proxy-Authorization
- TE
- Trailer
- Transfer-Encoding
- Upgrade
You can configure to specify only which headers to delete. Configuration example:
spring: cloud: gateway: filter: remove-hop-by-hop: # Multiple headers are separated by commas (,) headers: Connection,Keep-Alive
12,RemoveRequestHeader GatewayFilter Factory
Delete a Header for the original request, configuration example:
spring: cloud: gateway: routes: - id: removerequestheader_route uri: https://example.org filters: - RemoveRequestHeader=X-Request-Foo
Delete the request header named X-Request-Foo in the original request
13,RemoveResponseHeader GatewayFilter Factory
Delete a Header for the original response, configuration example:
spring: cloud: gateway: routes: - id: removeresponseheader_route uri: https://example.org filters: - RemoveResponseHeader=X-Response-Foo
Delete the response header named X-Request-Foo in the original response
14,RewritePath GatewayFilter Factory
Rewrite the original request path through a regular expression, configuring an example:
spring: cloud: gateway: routes: - id: rewritepath_route uri: https://example.org predicates: - Path=/foo/** filters: # Parameter 1 is the regular expression of the original path, and parameter 2 is the regular expression of the overridden path - RewritePath=/foo/(?<segment>.*), /$\{segment}
This configuration allows access to/foo/bar to rewrite the path to/bar and forward it, that is, to https://example.org/bar Note that due to YAML syntax, $\ is required to replace $
15,RewriteResponseHeader GatewayFilter Factory
Override a Header in the original response, configuration example:
spring: cloud: gateway: routes: - id: rewriteresponseheader_route uri: https://example.org filters: # Regular expression with Header name for parameter 1, value for parameter 2, and overridden value for parameter 3 - RewriteResponseHeader=X-Response-Foo, password=[^&]+, password=***
The meaning of this configuration is: if the value of X-Response-Foo in the response header is/42? User=ford&password=omg!what&flag=true, then it will be rewritten as/42? User=ford&password=***&flag=true, that is, password=omg!what was rewritten to password=***
16,SaveSession GatewayFilter Factory
Before forwarding the request, enforce the WebSession::save operation, configuration example:
spring: cloud: gateway: routes: - id: save_session uri: https://example.org predicates: - Path=/foo/** filters: - SaveSession
Mainly used for delayed data storage like Spring Session (data is not persisted immediately) and want to ensure session state is saved before request forwarding. If you use Spring Secution for Spring Session integration and want to ensure that security information is transmitted to downstream machines, you need to configure this filter.
17,secureHeaders GatewayFilter Factory
The secureHeaders filter factory is primarily a reference This blog The following Headers (including values) are added by default:
- X-Xss-Protection:1; mode=block
- Strict-Transport-Security:max-age=631138519
- X-Frame-Options:DENY
- X-Content-Type-Options:nosniff
- Referrer-Policy:no-referrer
- Content-Security-Policy:default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src https:; style-src 'self' https: 'unsafe-inline'
- X-Download-Options:noopen
- X-Permitted-Cross-Domain-Policies:none
If you want to modify the values of these Headers, you need to use the suffixes corresponding to these Headers, as follows:
- xss-protection-header
- strict-transport-security
- frame-options
- content-type-options
- referrer-policy
- content-security-policy
- download-options
- permitted-cross-domain-policies
Configuration example:
spring: cloud: gateway: filter: secure-headers: # Modify the value of X-Xss-Protection to 2;Mode=unblock xss-protection-header: 2; mode=unblock
If you want to disable some headers, you can use the following configuration:
spring: cloud: gateway: filter: secure-headers: # Separate multiple using commas (,) disable: frame-options,download-options
18,SetPath GatewayFilter Factory
Modify the original request path, configuration example:
spring: cloud: gateway: routes: - id: setpath_route uri: https://example.org predicates: - Path=/foo/{segment} filters: - SetPath=/{segment}
This configuration enables forwarding to when accessing ${GATEWAY_URL}/foo/bar https://example.org/bar That is, the original / foo/bar is modified to / bar
19,SetResponseHeader GatewayFilter Factory
Modify the value of a Header in the original response, configuration example:
spring: cloud: gateway: routes: - id: setresponseheader_route uri: https://example.org filters: - SetResponseHeader=X-Response-Foo, Bar
Modify the value of X-Response-Foo in the original response to Bar
20,SetStatus GatewayFilter Factory
Modify the status code of the original response, configuration example:
spring: cloud: gateway: routes: - id: setstatusstring_route uri: https://example.org filters: # String Form - SetStatus=BAD_REQUEST - id: setstatusint_route uri: https://example.org filters: # Number Form - SetStatus=401
The SetStatusd value can be either a number or a string. But be sure to use the values in the Spring HttpStatus enumeration class. Both configurations above can return the 401 HTTP status code.
21,StripPrefix GatewayFilter Factory
Path to truncate the original request, configuration example:
spring: cloud: gateway: routes: - id: nameRoot uri: http://nameservice predicates: - Path=/name/** filters: # Number indicates the number of paths to truncate - StripPrefix=2
As configured above, if the requested path is/name/bar/foo, it will be truncated into/foo and forwarded, that is, two paths will be truncated.
22,Retry GatewayFilter Factory
Retry for different responses, such as HTTP status codes, configuration example:
spring: cloud: gateway: routes: - id: retry_test uri: http://localhost:8080/flakey predicates: - Host=*.retry.com filters: - name: Retry args: retries: 3 statuses: BAD_GATEWAY
The following parameters can be configured:
- Retries: retries
- statuses: a status code that needs to be retried, in org.springframework.http.HttpStatus
- methods: Request method to retry, value in org.springframework.http.HttpMethod
- series: HTTP status code sequence, values in org.springframework.http.HttpStatus.Series
23,RequestSize GatewayFilter Factory
Set the size of the maximum request packet allowed to receive, configuration example:
spring: cloud: gateway: routes: - id: request_size_route uri: http://localhost:8080/upload predicates: - Path=/upload filters: - name: RequestSize args: # Unit is byte maxSize: 5000000
If the request packet size exceeds the set value, 413 Payload Too Large and an errorMessage are returned
24,Modify Request Body GatewayFilter Factory
Modify the original request body content before forwarding the request. This filter factory can only be configured through code and does not support configuration in a configuration file. Code example:
@Bean public RouteLocator routes(RouteLocatorBuilder builder) { return builder.routes() .route("rewrite_request_obj", r -> r.host("*.rewriterequestobj.org") .filters(f -> f.prefixPath("/httpbin") .modifyRequestBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE, (exchange, s) -> return Mono.just(new Hello(s.toUpperCase())))).uri(uri)) .build(); } static class Hello { String message; public Hello() { } public Hello(String message) { this.message = message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
Tips: This filter factory is in BETA state, API may change in the future, use caution in production environment
25,Modify Response Body GatewayFilter Factory
It can be used to modify the contents of the original response body, and the filter factory can only be configured through code, not in a configuration file. Code example:
@Bean public RouteLocator routes(RouteLocatorBuilder builder) { return builder.routes() .route("rewrite_response_upper", r -> r.host("*.rewriteresponseupper.org") .filters(f -> f.prefixPath("/httpbin") .modifyResponseBody(String.class, String.class, (exchange, s) -> Mono.just(s.toUpperCase()))).uri(uri) .build(); }
Tips: This filter factory is in BETA state, API may change in the future, use caution in production environment
26,Default Filters
Default Filters are used to add filter factories for all routes, that is, the filter factories configured through Default Filters work on all routes.Configuration example:
spring: cloud: gateway: default-filters: - AddResponseHeader=X-Response-Default-Foo, Default-Bar - PrefixPath=/httpbin
Official documents: