Nginx 反向代理:支持 WebSocket 协议
Nginx 反向代理可以将客户端请求转发到不同的服务器上进行处理,同时也可以支持 WebSocket 协议。
配置反向代理:
-
安装 Nginx
-
修改 Nginx 配置文件
在 Nginx 配置文件中添加以下内容:
http {
upstream backend {
server backend1.example.com;
server backend2.example.com;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
}
}
}
其中,backend1.example.com 和 backend2.example.com 分别是两个后端服务器的地址。
在 location / 中,proxy_pass 指定反向代理的地址,proxy_set_header 用于设置请求头,proxy_http_version 和 Connection、Upgrade 用于支持 WebSocket。
- 重启 Nginx
修改完配置文件后,需要重启 Nginx 服务使配置生效。
sudo service nginx restart
- WebSocket 支持
如果需要支持 WebSocket,需要在后端服务器上设置相应的配置。例如,在 Node.js 中使用 socket.io 库,可以添加以下代码:
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server);
io.on('connection', socket => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('chat message', msg => {
console.log('message: ' + msg);
io.emit('chat message', msg);
});
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
其中,io.emit('chat message', msg) 发送 WebSocket 消息。在 Nginx 配置文件中添加以下代码,用于转发 WebSocket 消息:
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_pass http://backend;
这样就可以实现 WebSocket 的反向代理了。
原文地址: https://www.cveoy.top/t/topic/lOIV 著作权归作者所有。请勿转载和采集!