Apache 反向代理 Http+WebSocket

自从 Socket.IO 1.0 (May 2014) 开始, 所有的 Connection 都以一个 HTTP polling Request 开始 (more info here)

这就意味着除了转发 WebSocket 之外,你还需要转发 任何 transport=polling 的 HTTP 请求。

下面的解决方案能正确地重定向所有 Socket 流量,而不会重定向其他不关于 Socket 的流量。

1. 开启 mods

1
sudo a2enmod rewrite proxy proxy_http proxy_wstunnel

或修改 httpd.conf

1
2
3
4
5
# 找到下面的这些行,并去除开头的 # 注释符号
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so

2. 对网站 *.conf 文件进行以下配置

例如:/etc/apache2/sites-available/mysite.com.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<VirtualHost *:80>
ServerName www.mydomain.com

# Enable the rewrite engine
# Requires: sudo a2enmod rewrite proxy proxy_http proxy_wstunnel
# In the rules/conds, [NC] means case-insensitve, [P] means proxy
RewriteEngine On

# socket.io 1.0+ starts all connections with an HTTP polling request
RewriteCond %{QUERY_STRING} transport=polling [NC]
RewriteRule /(.*) http://localhost:3001/$1 [P]

# When socket.io wants to initiate a WebSocket connection, it sends an
# "upgrade: websocket" request that should be transferred to ws://
RewriteCond %{HTTP:Upgrade} websocket [NC]
RewriteRule /(.*) ws://localhost:3001/$1 [P]

# OPTIONAL: Route all HTTP traffic at /node to port 3001
ProxyRequests Off
ProxyPass /node http://localhost:3001
ProxyPassReverse /node http://localhost:3001
</VirtualHost>

I’ve included an extra section for routing /node traffic that I find handy, see here for more info.

来自 stackoverflow.com

另外,go lang 来写的 WebSocket 功能前端跨域请求出现 403 错误,改一改就好了。

1
2
3
4
5
6
7
8
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
// 添加下面这个 ↓
CheckOrigin: func(r *http.Request) bool {
return true
},
}
本站文章除注明转载外均为原创,未经允许不要转载哇. ヾ(゚ー゚ヾ) http://qwqaq.com/665aacc7.html
分享到