首页 > 解决方案 > NodeJS Express 和 Apache 在同一台服务器上

问题描述

我有一个在 Apache 配置(/etc/apache2/sites-available/000-default.conf)中指定了多个虚拟主机的 VPS。

#Example config
<VirtualHost *:80>
    ServerName example.com
    Redirect / https://example.com/
    DocumentRoot /var/www/example
    ServerAdmin admin@example.com
</VirtualHost>

<VirtualHost *:80>
    ServerName sub.example.com
    DocumentRoot /var/www/sub.example
    ServerAdmin admin@example.com
</VirtualHost>

此外,我在使用端口 *:3000 运行的同一台服务器上安装了 Nodejs 应用程序。问题是,一些 ISP 阻止了该端口并且用户无法使用该应用程序(例如,在我的学校我无法访问该端口)。我希望这个应用程序将在端口 *:443 上运行,但我仍然想将 Apache 用于其他主机。有什么方法可以让应用程序与 Apache 位于相同的端口上,并且只有在用户访问域https://socket.example.com时才使用该应用程序,否则它将使用 Apache。我正在添加我的 Apache 服务器的示例配置和 nodejs 应用程序的一部分。

var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey = fs.readFileSync('/etc/letsencrypt/live/socket.example.com/privkey.pem', 'utf8');
var certificate = fs.readFileSync('/etc/letsencrypt/live/socket.example.com/cert.pem', 'utf8');
var bodyParser = require("body-parser");
var credentials = { key: privateKey, cert: certificate };
var express = require('express');
var app = express();
var port = 3000;
var httpsServer = https.createServer(credentials, app);


httpsServer.listen(port, function () {
    console.log('Server running on port: ' + port);
});


var urlencodedParser = bodyParser.urlencoded({ extended: false });

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.header('Access-Control-Allow-Credentials', 'true');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');

    if ('OPTIONS' == req.method) {
        res.writeHead(200);
        res.end();
    } else {
        next();
    }
});


app.get('/', function (req, res) {
    res.send(400);
    console.log("visit");
});

如果我忘记了某些事情,请告诉我,我会添加它。

标签: node.jsapacheexpress

解决方案


创建一个 Apache 虚拟主机,它将代理 node.js 应用程序的请求。您可以将 node.js 应用程序运行到任何可用端口,并通过 apache 代理它。

<VirtualHost *:443>
   ServerName yourdomain.com
   ServerAlias www.yourdomain.com
   DocumentRoot /var/www/defaultapp/
   Options -Indexes
   ErrorDocument 503 /check.html

   SSLProxyEngine On
   ProxyPass /check.html !
   ProxyPass / https://localhost:3000
   ProxyPassReverse / https://localhost:3000
   ProxyPreserveHost On

   SSLEngine on
   SSLCertificateFile /etc/apache2/ssl/domain.com.crt
   SSLCertificateKeyFile /etc/apache2/ssl/domain.com.key
   SSLCertificateChainFile /etc/apache2/ssl/domain.com:3000.ca-bundle
</VirtualHost>

详情请查看https://linuxtogether.org/configuring-reverse-proxy-for-node-using-apache-mod-proxy/


推荐阅读