如何从子域重定向到托管在Heroku的Angular+Node应用程序的HTTPS



已经为此挣扎了几天了。我有一个Angular 9应用程序,一个子域(subdomain.side.com(和一个运行Nodejs服务器的Heroku应用程序。Heroku应用程序具有SSL,并通过DNS正确连接到域面板,此外Heroku正在运行一个简单的服务器来启动该应用程序。

问题

我想将用户重定向到我的子域的HTTPS,例如,如果用户键入http://subdomain.side.com它将被重定向到HTTPS站点(https://subdomain.side.com)。

尝试

  1. 添加了.htaccess文件。还将其添加到prod文件夹中
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  1. 使用许多不同的设置配置server.js文件,最新的是:
const express = require('express');
const compression = require('compression');
const path = require('path');
const app = express();
app.use(compression());
app.use(express.static(__dirname + '/dist/APP'));
function ensureSecure(req, res, next) {
if (req.headers['x-forwarded-proto'] === 'https') {
return next();
}
res.redirect('https://' + req.hostname + req.url);
}
app.all('*', ensureSecure);
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/APP/index.html'));
});
app.listen(process.env.PORT || 8080);

这不是最漂亮的解决方案,但如果有人遇到同样的问题,这是一种变通方法。我在根路由中添加了一个保护,检查页面是否不是HTTPS,然后将其重定向到HTTPS,这并不理想,但。。。

if (location.protocol === 'http:') {
window.location.href = location.href.replace('http', 'https');
}

最新更新