无法连接到 Apache 后面的 Tomcat 网络套接字

Cannot connect to Tomcat web socket behind Apache

当我尝试从 Android stomp 客户端连接到 Spring Boot web socket 时,它没有连接并且 Catalina 日志显示

Handshake failed due to invalid Upgrade header: null

Tomcat 服务器 运行 在 Apache 之后,Apache 服务器在 https 上运行。 我没有在 Tomcat 中添加 https。所有的 http 请求都被重定向到 https 这就是我尝试连接到 websocket 的方式

mStompClient = Stomp.over(Stomp.ConnectionProvider.JWS, "wss://chat.example.com/ws/chat/websocket", headers);

但在本地计算机

中 运行 时有效
mStompClient = Stomp.over(Stomp.ConnectionProvider.JWS, "http://10.0.2.2:8080/chat/ws/chat/websocket", headers);

这是我的 stomp 终点设置

registry.addEndpoint("/chat").setHandshakeHandler(new HandShakeHandler()).withSockJS();

我启用了 mod proxy wstunnel 并在虚拟主机配置中添加了

ProxyPass / http://localhost:8080/chat/
proxyPassReverse / http://localhost:8080/chat/
ProxyPass /wss/ ws://localhost:8080/chat/

我该如何解决这个问题?

我从this server fault林那里得到了答案。我必须添加

RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]
RewriteCond %{HTTP:CONNECTION} Upgrade$ [NC]
RewriteRule /api/(.*) ws://newapp.example.com:8080/api/ [P]

并将最后一行更改为

RewriteRule /chat/(.*) ws://localhost:8080/chat/chat/ [P]

现在已连接

问题可能出在您的代理命令的顺序上:

ProxyPass / http://localhost:8080/chat/
proxyPassReverse / http://localhost:8080/chat/
ProxyPass /wss/ ws://localhost:8080/chat/

查看 documentation:

Ordering ProxyPass Directives

The configured ProxyPass and ProxyPassMatch rules are checked in the order of configuration. The first rule that matches wins. So usually you should sort conflicting ProxyPass rules starting with the longest URLs first.

由于第一个规则匹配 /wss/ 个 URL,后面的规则从不 触发。正确的顺序是:

ProxyPass /wss/ ws://localhost:8080/chat/
ProxyPass / http://localhost:8080/chat/
proxyPassReverse / http://localhost:8080/chat/

(我不确定你是否需要反向规则。)

我花了几个小时试图让重定向规则在我的系统上工作,但显然你根本不需要它们。