
本文详解如何通过 apache 的 mod_proxy_wstunnel 模块反向代理 websocket(如 python websockets 库启动的服务),解决连接被异常终止(1006 错误)的问题,并提供可直接部署的配置示例与关键注意事项。
本文详解如何通过 apache 的 mod_proxy_wstunnel 模块反向代理 websocket(如 python websockets 库启动的服务),解决连接被异常终止(1006 错误)的问题,并提供可直接部署的配置示例与关键注意事项。
要在 Apache 上成功运行 WebSocket 服务(例如基于 Python websockets 库搭建的后端),不能直接将 WebSocket 请求路由到静态文件或 HTTP 后端,而必须启用并正确配置 WebSocket 专用代理模块 —— mod_proxy_wstunnel。该模块专为升级后的 ws:// 和 wss:// 连接设计,能透传 Upgrade: websocket 头部及后续二进制帧,避免因协议不匹配导致连接被 Apache 强制关闭(典型错误:status code 1006 (ABNORMAL))。
✅ 正确配置步骤
1. 启用必要模块
确保以下 Apache 模块已启用(Ubuntu/Debian 示例):
sudo a2enmod proxy proxy_http proxy_wstunnel rewrite sudo systemctl restart apache2
⚠️ 关键:proxy_wstunnel 是 WebSocket 代理的核心模块,仅启用 proxy 和 proxy_http 不足以支持 WebSocket 升级。
2. 配置虚拟主机(VHost)
使用 ProxyPass 直接指向 ws:// 后端(注意协议前缀!):
<virtualhost>
ServerName mydomain.xyz
# 启用详细日志便于调试(生产环境建议设为 warn)
LogLevel info proxy:trace5
# 将 /ws 路径下的 WebSocket 请求代理至本地 ws://localhost:8080/
ProxyPass "/ws" "ws://localhost:8080/"
ProxyPassReverse "/ws" "ws://localhost:8080/"
# 静态资源仍由 Apache 服务
DocumentRoot "/var/www/html"
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</virtualhost>
✅ 关键细节说明:
Apache Superset 是一个广泛采用的开源 BI 平台,用于 SQL 探索、图表构建和仪表板交付。当代理需要查询仓库数据、组装仪表板或使用成熟的分析界面解释指标而不是临时笔记本代码时,此技能非常有用。
- ProxyPass "/ws" "ws://localhost:8080/" 中的 ws:// 协议标识触发 mod_proxy_wstunnel,而非默认的 HTTP 代理;
- 路径匹配需与前端客户端连接 URL 一致(如 ws://mydomain.xyz/ws/);
- ProxyPassReverse 确保响应头中的 Location 或 Upgrade 相关字段被正确重写;
- 不要添加 ProxyRequests Off(默认已关闭),也无需手动设置 Upgrade/Connection 头部——mod_proxy_wstunnel 自动处理。
3. 后端服务保持简洁
你的 server.py 逻辑正确,但建议增强健壮性:
import asyncio
import websockets
from rich.console import Console
console = Console()
clients = set()
async def handler(websocket):
clients.add(websocket)
console.log("[SYS] New client connected")
try:
# 可在此处接收/发送消息(示例)
async for message in websocket:
console.log(f"[MSG] Received: {message}")
await websocket.send(f"Echo: {message}")
except websockets.exceptions.ConnectionClosed:
console.log("[SYS] Client disconnected cleanly")
except Exception as e:
console.log(f"[ERR] Unexpected error: {e}")
finally:
clients.discard(websocket)
console.log("[SYS] Client removed")
async def main():
console.log("[SYS] Starting WebSocket server on :8080...")
async with websockets.serve(handler, "127.0.0.1", 8080): # 绑定 localhost 更安全
await asyncio.Future() # 运行至终止
if __name__ == "__main__":
asyncio.run(main())
? 安全提示:websockets.serve(..., "", 8080) 允许所有 IP 访问,生产环境应绑定 127.0.0.1 并依赖 Apache 做外网入口。
4. 客户端连接验证
前端 JavaScript 示例(确保路径与 ProxyPass 一致):
const ws = new WebSocket("ws://mydomain.xyz/ws/");
ws.onopen = () => console.log("✅ Connected");
ws.onmessage = (e) => console.log("←", e.data);
ws.onerror = (e) => console.error("❌ WS Error:", e);
? 常见错误与规避
- ❌ 错误配置 ProxyPass "/ws" "http://localhost:8080/" → 导致 1006(HTTP 代理无法处理 WebSocket 帧);
- ❌ 忘记启用 mod_proxy_wstunnel → Apache 日志中出现 AH01144: No protocol handler was valid for the URL;
- ❌ 使用 RewriteRule 替代 ProxyPass → 无法透传 Upgrade 流程;
- ❌ HTTPS 站点未配置 wss:// → 需启用 SSL 并使用 wss://localhost:8080/(后端需支持 TLS 或加一层 nginx 终止)。
完成上述配置后,重启 Apache 并测试连接,1006 错误将消失,WebSocket 全双工通信即可稳定建立。









