我的带有Spring Web MVC的SpringBoot2.2.0应用程序在反向代理后面运行。Spring如何正确处理X-Forwarded-{Prefix,Host,Proto}-header以识别对服务器的实际请求?
X-Forwarded-{Prefix,Host,Proto}
使用Spring Boot <= 2.1.x,您必须提供ForwardedHeaderFilter-Bean。从Spring Boot 2.2.0开始,您不再需要这样做。只需添加server.forward-headers-strategy=NATIVE或server.forward- headers-strategy=FRAMEWORK到您的application.properties-file。
ForwardedHeaderFilter
server.forward-headers-strategy=NATIVE
server.forward- headers-strategy=FRAMEWORK
application.properties
NATIVE表示Servlet容器(例如undertow,tomcat)正在解析x-forwarded-*-header,在大多数情况下都可以。如果依靠X-Forwarded- Prefix比你必须使用FRAMEWORK,以便request.getContextPath()设置正确。
NATIVE
x-forwarded-*
X-Forwarded- Prefix
FRAMEWORK
request.getContextPath()
例:
https://mydomain.tld/my-microservice/actuator
// Forwarded-Request from Reverse Proxy to your microservice GET http://localhost:8080/actuator/ X-Forwarded-Host: mydomain.tld X-Forwarded-Proto: https X-Forwarded-Prefix: /my-microservice
调试到HttpServletRequest中将导致:
request.getRequestURL(): "https://mydomain.tld/my-microservice/actuator/" request.getScheme(): "https" request.getContextPath(): "/my-microservice" new UrlPathHelper().getPathWithinApplication(request): "/actuator"