如何在具有不同域的同一 IP/服务器上托管多个 Node.js 站点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19254583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I host multiple Node.js sites on the same IP/server with different domains?
提问by Guy
I have a linux server with a single IP bound to it. I want to host multiple Node.js sites on this server on this IP, each (obviously) with a unique domain or subdomain. I want them all on port 80.
我有一个 linux 服务器,它绑定了一个 IP。我想在此 IP 上的此服务器上托管多个 Node.js 站点,每个站点(显然)都具有唯一的域或子域。我希望它们都在端口 80 上。
What are my options to do this?
我有什么选择来做到这一点?
An obvious solution seems to be to have all domains serviced by a node.js web app that acts as a proxy and does a pass through to the other node.js apps running on unique ports.
一个明显的解决方案似乎是让 node.js Web 应用程序为所有域提供服务,该应用程序充当代理并传递到在唯一端口上运行的其他 node.js 应用程序。
采纳答案by josh3736
Choose one of:
选择以下之一:
- Use some other server (like nginx) as a reverse proxy.
- Use node-http-proxyas a reverse proxy.
- Use the vhost middlewareif each domain can be served from the same Connect/Express codebase and node.js instance.
- 使用其他服务器(如 nginx)作为反向代理。
- 使用node-http-proxy作为反向代理。
- 如果可以从相同的 Connect/Express 代码库和 node.js 实例为每个域提供服务,请使用vhost 中间件。
回答by Adam
Diet.jshas very nice and simple way to host multiple domains with the same server instance. You can simply call a new server()for each of your domains.
Diet.js有非常好的和简单的方法来托管具有相同服务器实例的多个域。您可以简单地server()为每个域调用一个新的。
A Simple Example
一个简单的例子
// Require diet
var server = require('diet');
// Main domain
var app = server()
app.listen('http://example.com/')
app.get('/', function($){
$.end('hello world ')
})
// Sub domain
var sub = server()
sub.listen('http://subdomain.example.com/')
sub.get('/', function($){
$.end('hello world at sub domain!')
})
// Other domain
var other = server()
other.listen('http://other.com/')
other.get('/', function($){
$.end('hello world at other domain')
})
Separating Your Apps
分离您的应用程序
If you would like to have different folders for your apps then you could have a folder structure like this:
如果你想为你的应用程序设置不同的文件夹,那么你可以有这样的文件夹结构:
/server
/yourApp
/node_modules
index.js
/yourOtherApp
/node_modules
index.js
/node_modules
index.js
In /server/index.jsyou would require each app by it's folder:
在/server/index.js你需要每个应用程序的文件夹中:
require('./yourApp')
require('./yourOtherApp')
In /server/yourApp/index.jsyou would setup your first domainsuch as:
在/server/yourApp/index.js您将设置您的第一个域,例如:
// Require diet
var server = require('diet')
// Create app
var app = server()
app.listen('http://example.com/')
app.get('/', function($){
$.end('hello world ')
})
And in /server/yourOtherApp/index.jsyou would setup your second domainsuch as:
并且/server/yourOtherApp/index.js您将设置您的第二个域,例如:
// Require diet
var server = require('diet')
// Create app
var app = server()
app.listen('http://other.com/')
app.get('/', function($){
$.end('hello world at other.com ')
});
Read More:
阅读更多:
回答by Krasimir
Hm ... why you think that nodejs should act as a proxy. I'll suggest to run several node apps listening on different ports. Then use nginx to forward the request to the right port. If use a single nodejs you will have also single point of failure. If that app crashes then all the sites go down.
嗯……为什么你认为 nodejs 应该充当代理。我会建议运行几个节点应用程序来监听不同的端口。然后使用 nginx 将请求转发到正确的端口。如果使用单个 nodejs,您也会遇到单点故障。如果该应用程序崩溃,则所有站点都会关闭。
回答by Scott Puleo
Use nginx as a reverse proxy.
使用 nginx 作为反向代理。
http://www.nginxtips.com/how-to-setup-nginx-as-proxy-for-nodejs/
http://www.nginxtips.com/how-to-setup-nginx-as-proxy-for-nodejs/
Nginx brings a whole host of benefits to your applications in the form of caching, static file handling, ssl and load balancing.
Nginx 以缓存、静态文件处理、ssl 和负载平衡的形式为您的应用程序带来了许多好处。
回答by fuelusumar
I have an API I use on a site and below is my configuration. I also have it with SSL and GZIP, if someone needs it, just comment me.
我有一个在网站上使用的 API,下面是我的配置。我也有 SSL 和 GZIP,如果有人需要,请评论我。
var http = require('http'),
httpProxy = require('http-proxy');
var proxy_web = new httpProxy.createProxyServer({
target: {
host: 'localhost',
port: 8080
}
});
var proxy_api = new httpProxy.createProxyServer({
target: {
host: 'localhost',
port: 8081
}
});
http.createServer(function(req, res) {
if (req.headers.host === 'http://www.domain.com') {
proxy_web.proxyRequest(req, res);
proxy_web.on('error', function(err, req, res) {
if (err) console.log(err);
res.writeHead(500);
res.end('Oops, something went very wrong...');
});
} else if (req.headers.host === 'http://api.domain.com') {
proxy_api.proxyRequest(req, res);
proxy_api.on('error', function(err, req, res) {
if (err) console.log(err);
res.writeHead(500);
res.end('Oops, something went very wrong...');
});
}
}).listen(80);
回答by user568109
If you are using connect/express server, you can see the vhostmiddleware. It will allow multiple domains(sub-domains) to be used for the server address.
如果您使用连接/快速服务器,您可以看到vhost中间件。它将允许多个域(子域)用于服务器地址。
You can follow the example given here, which looks exactly like what you need.
您可以按照此处给出的示例进行操作,它看起来与您需要的完全一样。
回答by Saleh Hamadeh
The best way to do it is to use Express's vhost Middleware. Check out this tutorial for a step-by-step explanation:
最好的方法是使用 Express 的 vhost 中间件。查看本教程以获取分步说明:
http://shamadeh.com/blog/web/nodejs/express/2014/07/20/ExpressMultipleSites.html
http://shamadeh.com/blog/web/nodejs/express/2014/07/20/ExpressMultipleSites.html
回答by Kevin Le - Khnle
First install foreverand bouncy.
Then write a startup script. In this script, add a rule to the iptables firewall utility to tell it to forward the traffic on port 80 to port 8000 (or anything else that you choose). In my example, 8000 is where I run bouncy
然后写一个启动脚本。在此脚本中,向 iptables 防火墙实用程序添加一条规则,告诉它将端口 80 上的流量转发到端口 8000(或您选择的任何其他端口)。在我的示例中,8000 是我运行 bouncy 的地方
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8000
Using forever, let's tell the script to run bouncy on port 8000
使用永远,让我们告诉脚本在端口 8000 上运行 bouncy
forever start --spinSleepTime 10000 /path/to/bouncy /path/to/bouncy/routes.json 8000
The routes.json would something like
routes.json 会类似于
{
“subdomain1.domain.com" : 5000,
“subdomain2.domain.com" : 5001,
“subdomain3.domain.com" : 5002
}
NodeJS application1, application2 and application3 run on port 5000, 5001 and 5002 respectively.
NodeJS application1、application2 和 application3 分别运行在端口 5000、5001 和 5002 上。
The script I use in my case can be found hereand you might have to change a little to fit in your environment.
可以在此处找到我在案例中使用的脚本,您可能需要稍作更改以适应您的环境。
I also wrote about this in more details and you can find it here.
我还详细介绍了这一点,您可以在此处找到它。
回答by toshi
This is my simplest demo project without any middleware or proxy.
This requires only a few codes, and it's enough.
这是我最简单的演示项目,没有任何中间件或代理。
这只需要几个代码,就足够了。
https://github.com/hitokun-s/node-express-multiapp-demo
https://github.com/hitokun-s/node-express-multiapp-demo
With this structure, you can easily set up and maintain each app independently.
I hope this would be a help for you.
通过这种结构,您可以轻松地独立设置和维护每个应用程序。
我希望这对你有帮助。
回答by papiro
Here's how to do it using vanilla Node.js:
以下是使用 vanilla Node.js 的方法:
const http = require('http')
const url = require('url')
const port = 5555
const sites = {
exampleSite1: 544,
exampleSite2: 543
}
const proxy = http.createServer( (req, res) => {
const { pathname:path } = url.parse(req.url)
const { method, headers } = req
const hostname = headers.host.split(':')[0].replace('www.', '')
if (!sites.hasOwnProperty(hostname)) throw new Error(`invalid hostname ${hostname}`)
const proxiedRequest = http.request({
hostname,
path,
port: sites[hostname],
method,
headers
})
proxiedRequest.on('response', remoteRes => {
res.writeHead(remoteRes.statusCode, remoteRes.headers)
remoteRes.pipe(res)
})
proxiedRequest.on('error', () => {
res.writeHead(500)
res.end()
})
req.pipe(proxiedRequest)
})
proxy.listen(port, () => {
console.log(`reverse proxy listening on port ${port}`)
})
Pretty simple, huh?
很简单吧?

