Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: url route with the CNAME record

I want to map example.org and cname.example.org to two different node.js app. But use no http web server such as nginx.

And the web framework is express.

So is there are any middleware in express or node.js to do this?

like image 973
atupal Avatar asked Feb 25 '26 03:02

atupal


2 Answers

Express uses connect so you can do this:

var express = require('express'),
    app = express();

app.use(express.vhost('example.org', require('./exampleApp/')));
app.use(express.vhost('cname.example.org', require('./cnameExampleApp/')));

app.listen(80);

There is also an example on github: https://github.com/visionmedia/express/tree/master/examples/vhost

And here the reference for connect.vhost: http://www.senchalabs.org/connect/vhost.html

Edit: In recent express versions, most middlewares like vhost are not included, so you will have to install them manually.

First, run:

$ npm install --save vhost

Updated code snippet:

const express = require("express");
const vhost = require("vhost");

const app = express();

app.use(vhost("example.org", require("./exampleApp/")));
app.use(vhost("cname.example.org", require("./cnameExampleApp/")));

app.listen(80);
like image 86
iH8 Avatar answered Feb 27 '26 19:02

iH8


You need a proxy like nginx in anyway if your 2 node apps are hosted on the same host.

var request = require('request');    

var proxy = require('http').createServer(function (req, res) {    

    // distribute by request header 'host'
    var targetHost = req.headers.host;
    if (targetHost === 'example.org') {
      req.pipe(request('http://your-node-app1' + req.url)).pipe(res);
    } else if (targetHost === 'cname.example.org') {
      req.pipe(request('http://your-node-app2' + req.url)).pipe(res);
    } else { // not found or host is invalid
      res.statusCode = 404;
      res.end('host is not found!');
    }
});

proxy.listen(80); // assume it listens to port 80
like image 22
shawnzhu Avatar answered Feb 27 '26 18:02

shawnzhu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!