node.js - 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");
});
如果我忘记了某些事情,请告诉我,我会添加它。
解决方案
创建一个 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/
推荐阅读
- android - Android自定义ArrayAdapter在列表中呈现对象,而不是值
- wordpress - 如何利用 wordpress 模板层次结构根据类别名称/标签呈现不同的帖子模板?
- jquery - 在模式窗口中显示 pdf 而不是下载文件或在新选项卡中显示
- amazon-web-services - Redshift:如何列出组中的所有用户
- jquery - jQuery Alert 仅适用于 Firefox,不适用于 Chrome、Edge 或 IE
- java - Spring Data/Hibernate - 传播生成的密钥
- java - 从 txt 文件中读取数据的问题
- javascript - express-ejs-layout 使用不同的布局
- objective-c - AVFoundation - LayerInstruction + setCropRectangleRamp - 如何正确导出?
- python - If And 不接受第二次输入