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

前端 未结 12 683
轻奢々
轻奢々 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:08

    Diet.js has 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.

    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.js you would require each app by it's folder:

    require('./yourApp')
    require('./yourOtherApp')
    

    In /server/yourApp/index.js you would setup your first domain such as:

    // 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.js you would setup your second domain such as:

    // 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:

    • Read more about Diet.js
    • Read more about Virtual Hosts in Diet.js Read more about Server in Diet.js
    0 讨论(0)
  • 2020-11-28 01:12

    Use nginx as a reverse proxy.

    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.

    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2020-11-28 01:13

    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.

    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);
    
    0 讨论(0)
  • 2020-11-28 01:14

    If you are using connect/express server, you can see the vhost middleware. It will allow multiple domains(sub-domains) to be used for the server address.

    You can follow the example given here, which looks exactly like what you need.

    0 讨论(0)
  • 2020-11-28 01:18

    Choose one of:

    • Use some other server (like nginx) as a reverse proxy.
    • Use node-http-proxy as a reverse proxy.
    • Use the vhost middleware if each domain can be served from the same Connect/Express codebase and node.js instance.
    0 讨论(0)
提交回复
热议问题