我有两个单独的node.js应用程序运行在nginx后面。 这两个应用程序使用socket.io和express。 一个在5000端口上,另一个在5001端口上。但是我们需要通过端口80访问它们,这样当客户端访问http://example.com/app1时,它们被转发到第一个应用程序, http:// example.com/app2第二个应用程序。
当我们只有一个应用程序时,我们在nginx的Sites Enabledconfiguration文件中有这个设置:
location /app1/ { proxy_pass http://127.0.0.1:5000/; } location /socket.io { proxy_pass http://127.0.0.1:5000/socket.io/; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_http_version 1.1; }
这工作得很好。 但是,现在我们正在添加第二个应用程序,我不知道如何设置转发。 显然,socket.io不能再转发到5000,因为来自app2的连接需要连接到5001以上。
当然,必须有一种方法来指定socket.io转发作为每个应用程序的子域,但我不知道那会是什么。
任何build议,你可以给我会非常感激。
我有确切的问题,我发现这个简单的解决方法:
从你的js / html文件configuration你的客户端socket.io,以便从子目录中进行连接(默认的socket.io设置将使你的socket.io连接路由到http://example.com/ socket.io )。 你可以在这里find如何做到这一点: 从子目录中运行socket.io 。
所以你需要在你的客户端文件上:
var socket = io.connect('http://example.com', {path: "/app1socket"});
和其他应用程序:
var socket = io.connect('http://example.com', {path: "/app2socket"});
然后,像以前一样,为nginx中的每个应用程序套接字创build路由:
location /app1socket/ { proxy_pass http://127.0.0.1:3000/socket.io/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /app2socket/ { proxy_pass http://127.0.0.1:4000/socket.io/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; }
假设您的应用程序在nginx下运行的原因是将http请求代理到本地运行的应用程序,请通过标准设置保留您的服务器文件configuration。
var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); http.listen(4000, '127.0.0.1');
您现在可以在nginx下创build多个socket.io应用程序。
如果我正确地理解了你的问题,你只需要将每个位置redirect到不同的后端,每个后端都监听不同的端口,如下所示:
location /app1/ { proxy_pass http://127.0.0.1:5000/; } location /app2/ { proxy_pass http://127.0.0.1:5001/; }
注意结尾,replace原来的URI。 如果您希望将原始/app[12]/ URI转发到后端,请在<ip>:<port>对之后删除任何内容。