Вариант 1, разные app для каждого домена:
'use strict';
const http = require('http');
const express = require('express');
const appWWW = express();
const appSub = express();
http.createServer((req, res) => {
switch(req.headers.host) {
case 'example.com':
case 'www.example.com':
appWWW(req, res);
break;
case 'sub.example.com':
appSub(req, res);
break;
}
}).listen(8080);
Вариант 2, один app, переписываем url с помощью middleware:
'use strict';
const express = require('express');
const app = express();
const WWW_RE = /^www\./i;
app.use((req, res, next) => {
const host = req.headers.host.replace(WWW_RE, '');
req.url = '/' + host + req.url;
next();
});
app.listen(8080);