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

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

提交回复
热议问题