Server 1 : app1.js

var express = require('express');

var app = express();

app.use(function(req,res){

res.end("This is app1 i.e. first_app");

});

app.listen(8011);

Server 2 : app2.js

var express = require('express');

var app = express();

app.use(function(req,res){

res.end("This is app2 i.e. second_app");

});

app.listen(8012);

Server 3 : app3.js

var express = require('express');

var app = express();

app.use(function(req,res){

res.end("This is app3 i.e. third_app");

});

app.listen(8013);

Proxy Server : vhost.js





var http = require('http');

var http_proxy = require('http-proxy');





var options = {

'app1': 'http://127.0.0.1:8011',

'app2': 'http://127.0.0.1:8012',

'app3': 'http://127.0.0.1:8013',

}

var proxy = http_proxy.createProxy();

http.createServer(function(req, res) {

proxy.web(req, res, {

target: options[req.headers.host]

});

console.log(req.headers);

}).listen(8010);

command curl -X GET -H "Host: app1" http://127.0.0.1:8010

This is app1 i.e. first_app. Thus we have successfully implemented virtual hosting proxy servers in Node.js.

In this post we are going to learn about implementing virtual hosting proxy server in Node.js. A proxy is a way of routing requests from several different sources through one server whether its for caching, security or anything else. Virtual Hosting allows a single proxy server to host multiple domains and ports on a single IP address and port.Assume for a case, a few pages which are not openly available and somebody attempt to get to that, the page will be diverted to some other page. This sort of proxy is likewise called a forward proxy.A reverse proxy is a method for controlling how requests are sent to a server. For instance if a site is open by a huge number of client then to adjust load a portion of the requests will be diverted to some particular server, along these lines enhancing the general execution of the framework.To implement virtual hosting proxy servers in node.js, at first we will create 3 servers as shown below :Then we have to write a virtual host code using http-proxy as shown below :Save the file and run all the servers. Now when we run theit will give us the result asPlease Like and Share the Blog, if you find it interesting and helpful.