【问题标题】:Can't configure Nginx as Reverse Proxy for WebSocket无法将 Nginx 配置为 WebSocket 的反向代理
【发布时间】:2017-05-05 11:09:23
【问题描述】:

我的 Node.js 应用程序正在 localhost:8080 上运行 这些是服务器配置文件:

var express = require('express');
var http = require('http');
var app     = express();
var WS      = require('ws');
var config  = require('./config/main');
var Client  = require('./client');
// HTTP
var server = http.createServer(app);
app.use(express.static(__dirname + '/../client/build/'));
server.listen(config.httpPort, function() {
console.info('HTTP listening on *:' + config.httpPort);
});
// WebSocket
var ws = new WS.Server({server: server});
console.info('Websocket server created');
ws.on('connection', function(ws) {
var client = new Client(ws);
console.log('New conection:', client.id);
});

module.exports = {
/* HTTP  PORT */
httpPort: process.env.PORT || 8080,

/* WebSocket  PORT */
wsPort: process.env.PORT || 8081
};

所以我尝试使用 Nginx 的反向代理运行它:

location /myapp { 
    proxy_pass http://localhost:8080/; 
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

现在,当我链接到localhost/myapp 时,页面正常显示,加载了所有静态文件,但似乎没有 WebSocket 连接。 PS:我使用的是 Nginx V 1.11.7

配置有问题还是我遗漏了什么?谢谢

【问题讨论】:

  • 您是否将 HTTP 版本设置为 1.1?配置语法如下:proxy_http_version 1.1
  • 嘿@AlessandroAlinone,是的,我做到了,但它没有改变任何东西

标签: node.js nginx websocket port reverse-proxy


【解决方案1】:

更改客户端用于 WS 连接的 URL 解决了这个问题..

所以在我的客户端我改变了这一行: new WebSocket(location.origin.replace(/^http/, "ws")); 到这一行: new WebSocket("ws://localhost/myapp");

现在一切正常!

【讨论】:

  • 顺便说一下,这是我的配置,以防有人需要它location /myapp { proxy_pass http://localhost:8080/; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; 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"; }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-01
  • 1970-01-01
  • 2019-06-26
  • 2019-02-04
  • 1970-01-01
相关资源
最近更新 更多