How do I host multiple Node.js sites on the same IP/server with different domains?

前端 未结 12 892
轻奢々
轻奢々 2020-11-28 01:03

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 wa

12条回答
  •  孤街浪徒
    2020-11-28 01:12

    Here's how to do it using 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?

提交回复
热议问题