Hosting multiple websites on the same node.js server
Hello all,
As basic as it can be, I made a little boilerplate to show the solution I used to host different websites with different domains on the same Node.js server on Openshift.
Assume that we have different domain and subdomains that should be redirect to the proper static websites folder.
The minimum configuration we need is described by only two attributes: the domain and the folder path.
First declare a JSON named `vhosts.json` with your environments information:
[
{
"domain": "www.example.com",
"path": "public/example_com"
},
{
"domain": "subdomain.example.com",
"path": "public/subdomain_example_com"
},
{
"domain": "my.website.com",
"path": "public/my_website_com"
}
]
Then create a `server.js` with the following contents:
var fs = require('fs'),
path = require('path'),
express = require('express'), // npm install express --save
vhost = require('vhost'); // npm install vhost --save
// Global application declaration
var app = express();
// Shared routes
app.get('/health', function(req, res) {
res.writeHead(200);
res.end();
});
// Virtual hosts
var virtualHosts = JSON.parse(fs.readFileSync('vhosts.json', 'utf8'));
virtualHosts.forEach(function(virtualHost) {
var virtualHostApp = express();
virtualHostApp.use(express.static(path.join(__dirname, virtualHost.path)));
app.use(vhost(virtualHost.domain, virtualHostApp));
});
// Listen on port 8080
app.listen(8080);
With just these 20 lines of codes our Node.js instance will be ready to server our static websites.
A different approach should be taken if we want to consider each website as a dynamic express application. In that case you should `require` all the children express applications in the `server.js` file and pass them to `vhost`.
That’s all, really!
You can find this boilerplate on this Github repository.
Have an express day!
Great step you have define it is really helpful for all developer making a website on javascript