Skip to content

Instantly share code, notes, and snippets.

@Xmerr
Last active March 4, 2020 15:10
Show Gist options
  • Save Xmerr/45c6b62ca5af32b9b51edce4462990f7 to your computer and use it in GitHub Desktop.
Save Xmerr/45c6b62ca5af32b9b51edce4462990f7 to your computer and use it in GitHub Desktop.
Koa Subdomain Router
module.exports = {
host: "http://localhost",
apps: [
{
name: "strapi",
port: 3537,
redirect: "/admin",
sub: "admin"
},
{
name: "apis",
port: 3537,
sub: "api"
},
{
name: "obsMaster",
port: 8675,
sub: "obs"
},
{
name: "io",
port: 3501,
sub: "io"
},
{
name: "ui",
port: 3500,
sub: "*"
}
]
}
const Koa = require('koa');
const Subdomain = require('koa-subdomain');
const Router = require('koa-router');
const proxy = require('koa-proxy');
const { apps, host } = require('config');
const app = new Koa();
const subdomain = new Subdomain();
const createRouter = ({ port, redirect, sub }) => {
const router = new Router();
if(redirect) {
router.all('*', ctx => {
ctx.redirect(`${host}:${port}${redirect}/`);
})
} else {
router.all('*', proxy({
host: `${host}:${port}/`,
jar: true
}));
}
subdomain.use(sub, router.routes());
};
apps.forEach(app => createRouter(app));
app.use(subdomain.routes());
app.listen(80);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment