Charlie
Charlie

Reputation: 1756

Serving dynamic subdomain content from a subdirectory

I have a directory structure on my server like:

site-a/app/index.html
site-a/app/main.js
site-a/app/vendor.js
site-b/app/index.html
site-b/app/main.js
site-b/app/vendor.js

And so on.

I'd like to be able to create a server that can respond to these like:

curl http://site-a/app/

curl http://site-a/app/vendor.js

For the index.html file, I have something like this and it works:

    this.app.use((req, res) => {
      res.sendFile(path.join(process.env['SOURCE'], req.subdomains[req.subdomains.length - 1], '/app/index.html'));
    });

But I can't for the life of me figure out how to get express.static to work in a situation like this.

Bonus Credit: Any request that fails should load /app/index.html. It's an Angular application.

Anyone have any pointers?

Upvotes: 0

Views: 196

Answers (1)

cseitz
cseitz

Reputation: 1226

Perhaps this is what you are looking for?

app.use('/app', function(req, res, next) {
  let host = req.get('host'); // for some reason, subdomains wasn't working on localhost
  let site = host.includes('site-b') ? 'site-b' : 'site-a'; // conditional logic because ^^^
  let files = path.join(process.env['SOURCE'], site, 'app'); // file path to /app folder for that site
  express.static(files)(req, res, function() {
    res.sendFile(path.join(files, 'index.html')) // fallback to index.html
  })
});

express.static needs to be given the directory, not index.html. It'll automatically use index.html as the root.

I specify next function to express.static that, if it fails to find a file, just sends index.html anyway.

Let me know if you have any questions!

/app/site-a = http://site-a.localhost:port/app

/app/site-b = http://site-b.localhost:port/app

Upvotes: 2

Related Questions