6.15 删除请求参数
RemoveRequestParameter
可以删除指定名称的请求参数:
Example 40. application.yml
spring:
cloud:
gateway:
routes:
- id: removerequestparameter_route
uri: https://example.org
filters:
- RemoveRequestParameter=red
请求下发前,参数red会被删除。
6.16 重写地址
RewritePath 包含一个 regexp
正则表达式参数和一个 replacement
参数. 通过使用Java正则表达式灵活地重写请求路径。
Example 41. application.yml
spring:
cloud:
gateway:
routes:
- id: rewritepath_route
uri: https://example.org
predicates:
- Path=/red/**
filters:
- RewritePath=/red(?<segment>/?.*), $\{segment}
对于请求路径/red/blue
,将在发出下游请求之前将路径设置为/blue
。注意,由于YAML规范,请使用 $\
替换 $
。
6.17 重写location header
RewriteLocationResponseHeader
可以修改 Location header的值,从而隐藏一些后台路径细节。它的参数有stripVersionMode、locationHeaderName、hostValue和protocolsRegex。
Example 42. application.yml
spring:
cloud:
gateway:
routes:
- id: rewritelocationresponseheader_route
uri: http://example.org
filters:
- RewriteLocationResponseHeader=AS_IN_REQUEST, Location, ,
比如,有一个请求 POST api.example.com/some/object/name ,响应中Location header的值原来是object-service.prod.example.net/v2/some/object/id ,会被修改为api.example.com/some/object/id
stripVersionMode参数有三个取值:NEVER_STRIP、AS_IN_REQUEST(默认)和 ALWAYS_STRIP
NEVER_STRIP:
不删除路径中的版本号AS_IN_REQUEST:如果请求中没有版本号,则响应中的版本号会被删除
ALWAYS_STRIP:
删除路径中的版本号
如果提供了hostValue参数, 会用来替换掉响应中Location header的host:port 部分。如果没有提供该参数,则会使用请求中带的值。
protocolsRegex参数 必须要可以正确匹配到合法的协议名,否则不会产生效果。默认值是http|https|ftp|ftps。
6.18 修改响应header值
RewriteResponseHeader包含 name
, regexp
和 replacement
参数.。通过使用Java正则表达式灵活地重写响应头的值。
Example 43. application.yml
spring:
cloud:
gateway:
routes:
- id: rewriteresponseheader_route
uri: https://example.org
filters:
- RewriteResponseHeader=X-Response-Red, , password=[^&]+, password=***
对于一个/42?user=ford&password=omg!what&flag=true
的header值,在做下游请求时将被设置为/42?user=ford&password=***&flag=true
,由于YAML规范,请使用 $\
替换 $
。
6.19 保存session
SaveSession GatewayFilter 将请求转发到下游之前强制执行WebSession::save
操作。这在使用 Spring Session 之类时特别有用,需要确保会话状态在进行转发调用之前已保存。
Example 44. application.yml
spring:
cloud:
gateway:
routes:
- id: save_session
uri: https://example.org
predicates:
- Path=/foo/**
filters:
- SaveSession
如果你希望要将[Spring Security](https://projects.spring.io/Spring Security/)与Spring Session集成,并确保安全详细信息已转发到远程的进程,这一点至关重要。
6.20 添加 SecureHeaders
SecureHeaders
GatewayFilter 可以把以下header添加到响应头中(带默认值):
-
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)
对于这些header的详细说明,请看 HTTP Security Headers
spring.cloud.gateway.filter.secure-headers 中对应的属性如下:
-
xss-protection-header
-
strict-transport-security
-
x-frame-options
-
x-content-type-options
-
referrer-policy
-
content-security-policy
-
x-download-options
-
x-permitted-cross-domain-policies
下面的配置展示如何禁用默认header:
spring.cloud.gateway.filter.secure-headers.disable=x-frame-options,strict-transport-security
注意
header名称要用小写
6.21 修改请求路径
SetPath GatewayFilter Factory 采用 template
路径参数。它提供了一种通过允许路径的模板化segments来操作请求路径的简单方法。使用Spring Framework中的URI模板,允许多个匹配segments。
Example 45. application.yml
spring:
cloud:
gateway:
routes:
- id: setpath_route
uri: https://example.org
predicates:
- Path=/red/{segment}
filters:
- SetPath=/{segment}
对于一个 /red/bar
请求,在做下游请求前,路径将被设置为/bar
6.22 设置请求header
SetRequestHeader
需要指定 header的 name 和 value。
Example 46. application.yml
spring:
cloud:
gateway:
routes:
- id: setrequestheader_route
uri: https://example.org
filters:
- SetRequestHeader=X-Request-Red, Blue
这个filter 替换(不添加)指定的header。以上的配置会把 X-Request-Red:1234 替换为X-Request-Red:Blue。
SetRequestHeader 也可能使用URI变量匹配 path或host, 运行时改变header值:
Example 47. application.yml
spring:
cloud:
gateway:
routes:
- id: setrequestheader_route
uri: https://example.org
predicates:
- Host: {segment}.myhost.org
filters:
- SetRequestHeader=foo, bar-{segment}
6.23 设置响应header
SetResponseHeader GatewayFilter Factory 包括 name
和 value
参数.
Example 48. application.yml
spring:
cloud:
gateway:
routes:
- id: setresponseheader_route
uri: https://example.org
filters:
- SetResponseHeader=X-Response-Red, Blue
此GatewayFilter使用给定的名称替换所有header,而不是添加。因此,如果下游服务器响应为X-Response-Red:1234
,则会将其替换为X-Response-Red:Blue
,这是网关客户端将接收的内容。
SetResponseHeader 也可能使用URI变量匹配 path或host, 运行时改变header值:
spring:
cloud:
gateway:
routes:
- id: setresponseheader_route
uri: https://example.org
predicates:
- Host: {segment}.myhost.org
filters:
- SetResponseHeader=foo, bar-{segment}
6.24 设置httpstatus
SetStatus GatewayFilter Factory 包括唯一的 status
参数.必须是一个可用的Spring HttpStatus
。它可以是整数值404
或字符串枚举NOT_FOUND
。
Example 50. application.yml
spring:
cloud:
gateway:
routes:
- id: setstatusstring_route
uri: https://example.org
filters:
- SetStatus=BAD_REQUEST
- id: setstatusint_route
uri: https://example.org
filters:
- SetStatus=401
在这个例子中,HTTP返回码将设置为401.
也可设置为返回原请求的状态码:
Example 51. application.yml
spring:
cloud:
gateway:
set-status:
original-status-header-name: original-http-status
6.25 截取请求地址
StripPrefix GatewayFilter Factory 包括一个parts
参数。 parts
参数指示在将请求发送到下游之前,要从请求中去除的路径中的节数。
Example 52. application.yml
spring:
cloud:
gateway:
routes:
- id: nameRoot
uri: https://nameservice
predicates:
- Path=/name/**
filters:
- StripPrefix=2
当通过网关发出/name/bar/foo
请求时,向nameservice
发出的请求将是http://nameservice/foo
。
6.26 重试
Retry GatewayFilter Factory包括 以下
参数:
retries
: 重试次数statuses
:触发重试的HTTP状态代码,用org.springframework.http.HttpStatus
标识methods
:触发重试的HTTP方法,用org.springframework.http.HttpMethod
标识series
:触发重试的一系列状态码,用org.springframework.http.HttpStatus.Series
标识exceptions:
触发重试的异常列表backoff:配置重试对应的算法。每次重试的间隔算法为 firstBackoff * (factor ^ n), n为重试次数。如果配置了maxBackoff, 则间隔时间不能大于maxBackoff。如果配置了basedOnPreviousValue 为 true,则间隔算法为prevBackoff * factor。
如果开启重试功能,各个参数的默认值为:
-
retries
: 3 次 -
series
: 5XX series -
methods
: GET method -
exceptions
:IOException
和 TimeoutException
-
backoff
: disabled
Example 53. application.yml
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
methods: GET,POST
backoff:
firstBackoff: 10ms
maxBackoff: 50ms
factor: 2
basedOnPreviousValue: false
说明:
当 retry filter和 forward: 一起用的时候, 目标地址通过返回错误码的方式通知错误时,
不会触发重试;只有抛出异常或Mono.error(ex)的方式,才会触发重试。
注意:
重试时,如果请求中包含body,网关会缓存body,从而导致内存吃紧。
保存缓存的属性为ServerWebExchangeUtils.CACHED_REQUEST_BODY_ATTR,
类型为org.springframework.core.io.buffer.DataBuffer
6.27 限制请求大小
RequestSize GatewayFilter Factory可以限制请求大小。过滤器以RequestSize
作为参数,这是定义请求的允许大小限制。参数可以带位置,如 'KB' 或 'MB' , 默认是 ‘B’
Example 54. application.yml
spring:
cloud:
gateway:
routes:
- id: request_size_route
uri: http://localhost:8080/upload
predicates:
- Path=/upload
filters:
- name: RequestSize
args:
maxSize: 5000000
当请求因大小而被拒绝时, RequestSize GatewayFilter Factory 将响应状态设置为413 Payload Too Large
,并带有额外的header errorMessage
。下面是一个 errorMessage
的例子。
errorMessage : Request size is larger than permissible limit.
Request size is 6.0 MB where permissible limit is 5.0 MB
注意
如果未在路由定义中设置该参数,则默认请求大小将设置为5 MB。
6.28 修改请求host值
SetRequestHost filter可以把host修改为指定的值:
Example 55. application.yml
spring:
cloud:
gateway:
routes:
- id: set_request_host_header_route
uri: http://localhost:8080/headers
predicates:
- Path=/headers
filters:
- name: SetRequestHost
args:
host: example.org
请求的host值会被修改为example.org
6.29 修改请求body
ModifyRequestBody
可用于在请求主体被网关发送到下游之前对其进行修改。
注意
只能使用Java DSL配置此过滤器
@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;
}
}
6.30 修改响应body
ModifyResponseBody
可用于在将响应正文发送回客户端之前对其进行修改。
注意
只能使用Java DSL配置此过滤器
@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();
}
6.31 设置全局默认filters
spring.cloud.gateway.default-filters可以为所有路由添加默认filter列表:
Example 56. application.yml
spring:
cloud:
gateway:
default-filters:
- AddResponseHeader=X-Response-Default-Red, Default-Blue
- PrefixPath=/httpbin
Spring Cloud Gateway 2.2.3 官方使用说明(1)--路由
Spring Cloud Gateway 2.2.3 官方使用说明(2)-- 路由filter(上)
Spring Cloud Gateway 2.2.3 官方使用说明(2)-- 路由filter(下)
Spring Cloud Gateway 2.2.3 官方使用说明(3)-- Global filter
Spring Cloud Gateway 2.2.3 官方使用说明(4)-- HttpHeader Filters
Spring Cloud Gateway 2.2.3 使用说明(5)-- TLS 和 SSL
Spring Cloud Gateway 2.2.3 使用说明(6)-- 其它配置
Spring Cloud Gateway 2.2.3 使用说明(7)-- actuator
Spring Cloud Gateway 2.2.3 使用说明(8)-- 开发指导