DEV Community

Akram Khan
Akram Khan

Posted on

My subdomain proxy server in nodejs

Here is the nodejs proxy server that can be use to listen subdomain routes.

for example I run a server is localhost:5000 but I want to use subdomain in this like subdomain1.localhost:5000 or something diferent.

const express = require('express');
const app = express();
const httpProxy = require('http-proxy');

const proxy = httpProxy.createProxy();

const BASE = "https://github.com";

app.use((req, res, next) => {

     const hostname = req.hostname;
     const domains = hostname.split('.');
     const subdomain = domains[0];
     const resolveTo = BASE + '/' + subdomain;
     return proxy.web(req, res, { target: resolveTo, changeOrigin: true });
});

app.listen(5000, () => console.log('Listening on port: 5000'));

app.get('/', (req, res) => {
     return res.send('Welcome to the homepage');
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)