[英]Express.js redirect to HTTPS and send index.html
I have a simple Express.js instance that's serving up static assets for a single page Angular app. 我有一个简单的Express.js实例,它为单页Angular应用程序提供静态资源。 I set up some middleware on the Express config so that index.html is returned for all routes and Angular can load from there.
我在Express配置上设置了一些中间件,以便为所有路由返回index.html,Angular可以从那里加载。
More recently, I set up SSL on Heroku and I want to make sure that all traffic that comes in from HTTP is redirected to HTTPS. 最近,我在Heroku上设置了SSL,我想确保从HTTP传入的所有流量都被重定向到HTTPS。 I tried to combine the suggested solution from this post with what I have now, but end up in an endless redirect loop.
我试图将这篇文章中建议的解决方案与我现在的解决方案结合起来,但最后还是在无休止的重定向循环中。
In short, I need all traffic to be redirected from HTTP to HTTPS and the index.html file to be sent for all requests. 简而言之,我需要将所有流量从HTTP重定向到HTTPS,并为所有请求发送index.html文件。 What am I doing wrong here?
我在这做错了什么?
var gzippo = require('gzippo');
var express = require('express');
var morgan = require('morgan');
var app = express();
// set environment variables
var env = app.get('env') || 'development';
app.use(morgan('dev'));
// serve static assets
app.use(gzippo.staticGzip("" + __dirname + "/dist"));
app.use("/js", express.static(__dirname + "/dist/scripts"));
app.use("/fonts", express.static(__dirname + "/fonts"));
app.use("/img", express.static(__dirname + "/dist/assets/images"));
app.use("/css", express.static(__dirname + "/dist/styles"));
// Redirect all HTTP traffic to HTTPS
function ensureSecure(req, res, next){
if(req.secure){
// OK, continue
return next();
};
res.redirect('https://'+req.hostname+req.url); // handle port numbers if you need non defaults
};
// Always send index.html
function sendIndex(req, res, next) {
res.sendfile('index.html', { root: __dirname + "/dist/"});
}
// Handle environments
if (env == 'production') {
app.all('*', ensureSecure);
}
app.all('/*', sendIndex);
// Start server
app.listen(process.env.PORT || 5000);
Heroku terminates SSL connections at the load balancer level, so req.secure
will never be true, because your connection to heroku's load balancer is not using SSL, thus creating an infinite redirect loop. Heroku在负载均衡器级别终止SSL连接,因此
req.secure
永远不会成立,因为您与heroku的负载均衡器的连接不使用SSL,因此创建了无限重定向循环。
You have to check the X-Forwarded-Proto
header instead: 您必须检查
X-Forwarded-Proto
标头:
if(req.headers["x-forwarded-proto"] === "https"){
// OK, continue
return next();
};
res.redirect('https://'+req.hostname+req.url);
Edit: you can also set app.enable("trust proxy")
to have express check the headers automatically. 编辑:您还可以设置
app.enable("trust proxy")
以自动快速检查标题。 See http://expressjs.com/guide/behind-proxies.html 请参阅http://expressjs.com/guide/behind-proxies.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.