You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

配置Apache反向代理实现WSS外网访问:连接失败问题排查

问题描述

我正尝试配置Apache,让外网设备/电脑能通过ngrok这类隧道客户端访问本地服务。目前HTML页面及其他资源能正常加载,但WSS无法连接。浏览器报错:

Firefox could not establish connection with
wss://example.com/ws/locationOf_wsfile

我的Apache配置如下:

<VirtualHost *:80>
    ServerName localhost
    Redirect permanent / https://example.com/
</VirtualHost>
<VirtualHost *:443>
    ServerName example.com
    
        ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # enable HTTP/2, if available
    Protocols h2 http/1.1

    SSLEngine on
    SSLProxyEngine on
    SSLCertificateFile /etc/example.com.crt
    SSLCertificateKeyFile /etc/example.com.key

    Header always set Strict-Transport-Security "max-age=63072000"

    DocumentRoot "/usr/share/web_static_files"
    <Directory "/usr/share/web_static_files">
        Options Indexes MultiViews Includes FollowSymLinks
        AddOutputFilter Includes html
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>

   <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "GET,POST,PUT,DELETE,OPTIONS"
    Header set Access-Control-Allow-Headers "Content-Type,Authorization,X-Requested-With"
    Header set Access-Control-Allow-Credentials "true"
   </IfModule>

    ProxyPreserveHost on
    ProxyPass / http://localhost:5320/
    ProxyPassReverse / http://localhost:5320/
    ProxyPass /ws-id ws://localhost:8450/ws-id
    ProxyPassReverse /ws-id ws://localhost:8450/ws-id

    RewriteEngine on
    RewriteRule ^/([a-zA-Z0-9]+)$ /index.html
    
</VirtualHost>

# Mozilla Guideline v5.4, Apache 2.4.41, OpenSSL 1.1.1d, intermediate configuration, no OCSP
SSLProtocol         all -SSLv3 -TLSv1.1
SSLHonorCipherOrder off
SSLSessionTickets   off
解决方案

1. 修正路径匹配

浏览器请求的是/ws/locationOf_wsfile,但当前配置只代理了/ws-id路径,两者不匹配。可以二选一调整:

  • 修改ProxyPass规则匹配请求路径:
    ProxyPass /ws ws://localhost:8450/ws
    ProxyPassReverse /ws ws://localhost:8450/ws
    
  • 调整前端WSS连接地址为wss://example.com/ws-id/locationOf_wsfile,与配置的代理路径对齐。

2. 启用WebSocket代理模块

Apache必须加载mod_proxy_wstunnel才能处理WSS到WS的转发,执行以下命令启用:

a2enmod proxy_wstunnel
systemctl restart apache2

3. 调整ProxyPass顺序

ProxyPass /会匹配所有请求,必须把WebSocket的代理规则放在全局代理前面,否则WS请求会被错误转发到5320端口的服务:

# 先配置WS代理
ProxyPass /ws ws://localhost:8450/ws
ProxyPassReverse /ws ws://localhost:8450/ws
# 再配置全局代理
ProxyPass / http://localhost:5320/
ProxyPassReverse / http://localhost:5320/

4. 排除WS路径的Rewrite规则

当前RewriteRule会把单段路径重写到index.html,可能干扰WS请求,需要排除/ws开头的路径:

RewriteEngine on
# 跳过WS路径的重写
RewriteCond %{REQUEST_URI} !^/ws/
RewriteRule ^/([a-zA-Z0-9]+)$ /index.html

5. 检查SSL配置

确保SSLProxyEngine on已开启,证书文件路径正确且有效,避免SSL握手失败导致WSS连接异常。

内容的提问来源于stack exchange,提问作者William Page

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 13:22:13