Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Websocket协议的反向代理配置

By: wayen
22 July 2023 at 11:20

Websocket协议的反向代理配置

发表于|更新于|实用教程
|字数总计:321|阅读时长:1分钟|阅读量:

说明

Websocket(简称ws)是一种双向通信协议,使用与HTTP协议相同的端口,并通过HTTP_Upgrade机制来进行握手建立连接。而使用HTTP协议的反向代理可能对Websocket不起作用,所以本教程主要介绍基于Caddy2、Nginx、Apache2的Websocket反向代理配置。

Caddy2

1
2
3
4
5
6
xml.wiki {
tls /root/cert/pem /root/cert/key #或由Caddy自动申请
reverse_proxy localhost:7890 #所有代理请求
reverse_proxy /xml/* localhost:7890 #/xml开头的请求代理
reverse_proxy /xml{http.request.uri.path} localhost:7890{http.request.uri.path} #保留原始请求路径的路由
}

Nginx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
server {
listen 443 ssl;
server_name xml.wiki;
ssl_certificate /root/cert/pem;
ssl_certificate_key /root/cert/key;
ssl_session_timeout 5m;

location / {
proxy_redirect off;
proxy_pass http://127.0.0.1:7890;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

Apache2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
sudo a2enmod ssl rewrite proxy proxy_http proxy_wstunnel
nano /etc/apache2/sites-available/000-default.conf

<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName xml.wiki
SSLEngine on
SSLCertificateFile /root/cert/pem
SSLCertificateKeyFile /root/cert/key
ProxyRequests off
ProxyPreserveHost on
RewriteEngine on
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
#反向代理http请求
ProxyPass / http://localhost:7890/
ProxyPassReverse / http://localhost:7890/
#反向代理websocket连接
RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]
RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC]
RewriteRule .* ws://localhost:7890%{REQUEST_URI} [P]
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</IfModule>

systemctl reload apache2
文章作者: wayen
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Wayen

评论
数据库加载中

❌
❌