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

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

    Based on @Michaaatje and @papiro, a very easy way:

    Say you have some typical pages such as...

    var app = express()
    app.use(sess)
    app.use(passport.initialize())
    app.use(passport.session())
    app.use('/static', express.static('static'))
    
    app.get('/', ensureLoggedIn("/loginpage"), function(req, res, next) {
        ...
    })
    
    app.get('/sales', ensureLoggedIn("/loginpage"), function(req, res, next) {
        ...
    })
    
    app.get('/about', ensureLoggedIn("/loginpage"), function(req, res, next) {
        ...
    })
    
    app.post('/order', ensureLoggedIn("/loginpage"), urlencodedParser, (req, res) => {
        ...
    })
    

    .. and so on.

    Say the main domain is "abc.test.com"

    But you have an "alternate" domain (perhaps for customers) which is "customers.test.com".

    Simply add this ...

    var app = express()
    app.use(sess)
    app.use(passport.initialize())
    app.use(passport.session())
    app.use('/static', express.static('static'))
    
    app.use((req, res, next) => {
        req.isCustomer = false
        if (req.headers.host == "customers.test.com") {
            req.isCustomer = true
        }
        next();
    })
    

    and then it is this easy ...

    app.get('/', ensureLoggedIn("/loginpage"), function(req, res, next) {
        if (req.isCustomer) {
            .. special page or whatever ..
            return
        }
        ...
    })
    
    app.get('/sales', ensureLoggedIn("/loginpage"), function(req, res, next) {
        if (req.isCustomer) {
            res.redirect('/') .. for example
            return
        }
        ...
    })
    
    app.get('/about', ensureLoggedIn("/loginpage"), function(req, res, next) {
        if (req.isCustomer) { ... }
        ...
    })
    
    app.post('/order', ensureLoggedIn("/loginpage"), urlencodedParser, (req, res) => {
        if (req.isCustomer) { ... }
        ...
    })
    

    Thanks to @Michaaatje and @papiro .

提交回复
热议问题