Node.js从URL中删除端口

时间:2017-08-23 09:07:50

标签: node.js apache .htaccess vhosts express-vhost

我的服务器中有两个 Node.js 应用。它们列在端口55555中。这是目录结构。

/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内容

'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内容

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]

当我尝试访问www.foo.com时,我收到的错误为:

  

无法获取/foo.com/index.html.var

当我尝试访问www.bar.com时,我收到的错误为:

  

无法获得/bar.com/index.html.var

但我可以使用www.foo.com:55555www.bar.com:55555

等端口访问这两个网站

如何在不使用端口的情况下访问网站?

1 个答案:

答案 0 :(得分:-1)

使用Apache作为应用程序的反向代理可以解决您的问题:

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

为此使用mod_proxy扩展名。 更多信息请参见this digitalocean article