Spring Boot 在 Apache 代理后面嵌入 Tomcat

2024-02-14

我们有一个 Spring Boot (Spring MVC) 应用程序,在 Apache SSL 代理后面的专用应用程序服务器上嵌入了 Tomcat。

代理服务器上的 SSL 端口是 4433,转发到应用程序服务器上的端口 8080。

所以代理服务器的 URL 转发如下:

https://proxyserver:4433/appname   >>forward>>   http://appserver:8080/

当没有代理运行时,首先发生的事情是
Spring Security 重定向请求,例如:

http://appserver:8080/   >>redirect>>   http://appserver:8080/login

显示登录表单,通过扩展WebSecurityConfigurerAdapter with

  ...
  httpSecurity.formLogin().loginPage("/login") ...
  ...

没有代理它工作正常,但使用代理时需要更改重定向,
所以 Spring 应该重定向到相应的代理 URL,例如:

http://appserver:8080/   >>redirect>>   https://proxyserver:4433/appname/login

但还没有成功。

我正在尝试应用这个解决方案:59.8 在前端代理服务器后面使用 Tomcat https://docs.spring.io/spring-boot/docs/1.1.1.RELEASE/reference/html/howto-embedded-servlet-containers.html#howto-use-tomcat-behind-a-proxy-server

我们已经配置了模组代理 https://en.wikipedia.org/wiki/Mod_proxy在 Apache 中,并验证它发送了预期的标头:

X-Forwarded-For: xxx.xxx.xxx.xxx
X-Forwarded-Host: proxyserver
X-Forwarded-Port: 4433
X-Forwarded-Proto: https

应用程序以参数启动:

export ARG1='-Dserver.tomcat.protocol-header=x-forwarded-proto' 
export ARG2='-Dserver.tomcat.remote-ip-header=x-forwarded-for'
java $ARG1 $ARG2 -jar webapp.jar

重定向仍然不起作用。

它将继续在本地重定向到http://appserver:8080/login这是客户无法获得的。

为了让这个场景发挥作用,我们还需要做些什么吗?


UPDATE

另外,我还担心代理 URL 中的“/appname”部分。在应用程序服务器上,应用程序的根目录为“/”。当通过代理时,应该如何指示 Spring 将“/appname”包含在发送回客户端的所有 URL 中?


前几天我也遇到了同样的问题。经过对 Spring Boot 1.3 的一些调试,我找到了以下解决方案。

1.您必须在 Apache 代理上设置标头:

<VirtualHost *:443>
    ServerName www.myapp.org
    ProxyPass / http://127.0.0.1:8080/
    RequestHeader set X-Forwarded-Proto https
    RequestHeader set X-Forwarded-Port 443
    ProxyPreserveHost On
    ... (SSL directives omitted for readability)
</VirtualHost>

2.您必须告诉您的 Spring Boot 应用程序使用这些标头。因此,请将以下行放入 application.properties 中(或 Spring Boots 理解属性的任何其他位置):

server.use-forward-headers=true

如果您正确执行这两件事,您的应用程序发送的每个重定向都会not go to http://127.0.0.1:8080/[路径] http://127.0.0.1:8080/%5Bpath%5D但自动到https://www.myapp.com/[路径] https://www.myapp.com/%5Bpath%5D

更新1。关于这个主题的文档是here https://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-web-servers.html#howto-use-tomcat-behind-a-proxy-server。您应该阅读它至少了解该属性server.tomcat.internal-proxies它定义了可以信任的代理服务器的 IP 地址范围。

2021 年更新文档已移至here https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-use-behind-a-proxy-server。 Spring Boot 配置现在有点不同。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Boot 在 Apache 代理后面嵌入 Tomcat 的相关文章

随机推荐