Node.js Remove the port from the URL

1.7k views Asked by At

I have two Node.js apps in my server. They are listing to port 55555. Here is the directory structure.

/home/myuser
  /.htaccess
  /package.json
  /server.js

  /foo.com
    /node_modules
    /public
      /index.html
   /package.json
   /server.js

  /bar.com
    /node_modules
    /public
      /index.html
   /package.json
   /server.js

/home/myuser/server.js content

'use strict';

// Module dependencies.
var express = require('express');
var vhost = require('vhost');

var port = process.env.PORT || 55555;   

function createVirtualHost(domainName, nodeApp) {
    return vhost(domainName, nodeApp);
}

//Create server
var app = express();

var fooApp = require('./foo.com/server.js').app;
var barApp = require('./bar.com/server.js').app;

//Create the virtual hosts
var fooHost = createVirtualHost("www.foo.com", fooApp);
var barHost = createVirtualHost("www.bar.com", barApp);

//Use the virtual hosts
app.use(fooHost);
app.use(barHost);

//Start server
app.listen( port, function() {
    console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});

/home/myuser/.htaccess content

RewriteEngine On
RewriteRule ^$ http://127.0.0.1:55555/ [P,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ http://127.0.0.1:55555/$1 [P,L]

When I trying to access www.foo.com, I am getting error as:

Cannot GET /foo.com/index.html.var

When I trying to access www.bar.com, I am getting error as:

Cannot GET /bar.com/index.html.var

But I can access both sites using port like www.foo.com:55555 and www.bar.com:55555

How could I access sites without using port?

1

There are 1 answers

0
tbking On

Using Apache as reverse proxy for your app can solve your problem:

<VirtualHost *:80>
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:8080/
    ProxyPassReverse / http://127.0.0.1:8080/
</VirtualHost>

Use mod_proxy extension for this. More information is provided in this digitalocean article.