expressjs / vhost

virtual domain hosting
MIT License
761 stars 87 forks source link

How to have *.domain.com and domain.com work together? #33

Closed AxelTerizaki closed 5 years ago

AxelTerizaki commented 5 years ago

Here's my problem, I hope someone can help.

I'm trying to write an app which, depending on the subdomain accessed, proxifies the user to another webapp listening to each a different port.

Exemple :

There's also a React app on domain.com (without any subdomain).

My problem lies in the fact that it doesn't work at all.

My current code is like this

app.use(vhost(`${conf.Frontend.Host}`, mainApp));
app.use(vhost(`*.${conf.Frontend.Host}`, getKMRoom), proxy(redirectKMRoom, {
        memoizeHost: false
    }));

...

unction getKMRoom(req, res, next) {
    const instance = getInstanceRoom(req.vhost[0]);
    if (!instance) {
        res.status(404).send('No room exists by this name');
    } else {
        req.KMAppPort = instance.port;
        next();
    }
}

function redirectKMRoom(req) {
    return `http://localhost:${req.KMAppPort}`;
}

In this configuration, when I access domain.com I get my react app (mainApp is called) but not with aaaa.domain.com. It never goes through and isn't picked by any route. Actually, getKMRoom isn't even called.

I'd like to understand what I'm doing wrong there, if anyone knows?

Thanks in advance.

kylehotchkiss commented 5 years ago

I'm new to this project myself, but are you using Heroku or AppEngine by any chance? It's possible the hostname isn't passing to your app correctly.

to test this theory, add app.use(function( req, res, next) { console.log( req.hostname ) }); above your app.use calls and if the hostname isn't conf.Frontend.Host, it's possible you'll need to turn on an express parameter to forward the hostname to your app correctly:

app.use('trust proxy')

Read more here: https://expressjs.com/en/guide/behind-proxies.html and here https://stackoverflow.com/questions/23413401/what-does-trust-proxy-actually-do-in-express-js-and-do-i-need-to-use-it to make sure this doesn't have any unexpected side effects

AxelTerizaki commented 5 years ago

Thanks for your message. While it didn't solve my problem (I already had trust proxy enabled) it spun me into the right direction. The problem was likely on my apache config since I had commented out the ServerAlias *.domain.com` directive for some tests. Now that i's uncommented, I'm getting hits when using the subdomains and it's properly routed.

I'll close the issue for now since it seems to work, and will reopen it if I still have issues.

Thanks again :)