我有一个VPS,其中包含在Apache配置(/etc/apache2/sites-available/000-default.conf)中指定的多个虚拟主机。
#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");
});
如果我忘记了什么,请告诉我,我将其添加。
答案 0 :(得分:1)
创建一个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/了解详情