我想在同一台服务器上运行 Sails.js API 的两个实例。我只有一个域名,想要这样的域名:
- v1.0 在 https://api.example.com/1.0/ 上运行
- v1.1 在 https://api.example.com/1.1/ 上运行
Sails/Express/Node.js 怎么可能?是否有任何模块可以处理此类问题?还是我需要像 Apache 或 Nginx 这样的代理服务器?
最佳答案
你可以用 node-http-proxy 来做
例如,您在端口 8080 上 sails 服务器 1,在端口 8081 上 sails 服务器 2。 现在,通过端口 80 上的 http-proxy,您可以将/1.0/重定向到服务器 1,将 v1.1 重定向到服务器 2。
这是您可以使用的 http-proxy 示例(未测试):
var http = require('http'), httpProxy = require('http-proxy'), proxy = httpProxy.createProxyServer({}), url = require('url');
proxy.on("error", function(err){console.log(err);});//Prevent proxy crash by socket hang out error
var proxyServer = http.createServer(function (req, res)
{
var hostname = req.headers.host.split(":")[0];
switch (hostname+req.url)
{
case 'api.example.com/1.0':
proxy.web(req, res, {target : 'http://localhost:8080'});
break;
case 'api.example.com/1.1':
proxy.web(req, res, {target : 'http://localhost:8081'});
break;
default:
proxy.web(req, res, {target : 'http://localhost:8080'});
}
});
//
// Listen to the `upgrade` event and proxy the
// WebSocket requests as well.
//
proxyServer.on('upgrade', function (req, socket, head)
{
var hostname = req.headers.host.split(":")[0];
switch (hostname+req.url)
{
case 'api.example.com/1.0':
proxy.ws(req, socket, {target : 'ws://localhost:8080'});
break;
case 'api.example.com/1.1':
proxy.ws(req, socket, {target : 'ws://localhost:8081'});
break;
default:
proxy.ws(req, socket, {target : 'ws://localhost:8080'});
}
});
proxyServer.listen(80, function ()
{
console.log('proxy listening on port 80');
});
你可以用 Apache 或 Nginx 做同样的事情,但你需要完整的 Node 解决方案:)
关于node.js - 如何在同一台服务器上运行多个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31849756/