1个node.js服务器上的多个子域

时间:2018-08-07 22:22:29

标签: node.js express subdomain

我想在一台服务器上创建一个包含多个Web应用程序(大约3-5个node.js + express应用程序)的系统。我也只有一个域。因此,我认为除了主应用程序之外,我还需要为每个应用程序创建子域。

我的问题是-如何将进入某些子域的用户重定向到正确的应用程序?我是否需要使用虚拟机,然后根据其子域将每个用户重定向到不同的VM(IP地址)?我什至会怎么做?

还是可以仅使用不同的端口号在同一服务器上运行每个应用程序?还是我没有真正想到的其他方式?

哪种方法最干净,我将如何实施?

1 个答案:

答案 0 :(得分:-1)

实现此目的的一种非常常见的方法是在不同的端口上运行每个节点服务器,然后设置诸如nginx之类的反向代理,使其根据传入HTTP的主机标头的匹配来转发请求。要求。

您当然可以通过自己检查host标头并将每个请求转发到关联端口上的适当节点服务器,来通过节点手动处理此问题。

以下是一些Node代码,它们说明了我所指的内容:

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}`)
})