Express.jsredirect到HTTPS并发送index.html

我有一个简单的Express.js实例,为单个页面的Angular应用程序提供静态资源。 我在Expressconfiguration中设置了一些中间件,这样所有的路由都会返回index.html,Angular可以从那里加载。

最近,我在Heroku上设置了SSL,我想确保所有来自HTTP的stream量都被redirect到HTTPS。 我试图将这篇文章中的build议解决scheme与我现在所拥有的解决scheme结合起来,但最后却是无尽的redirect循环。

简而言之,我需要将所有stream量从HTTPredirect到HTTPS,并且需要为所有请求发送index.html文件。 我在这里做错了什么?

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终止在负载平衡器级别的SSL连接,所以req.secure永远不会是真的,因为你连接到heroku的负载平衡器不使用SSL,从而创build一个无限的redirect循环。

您必须检查X-Forwarded-Proto标题:

 if(req.headers["x-forwarded-proto"] === "https"){ // OK, continue return next(); }; res.redirect('https://'+req.hostname+req.url); 

编辑:你也可以设置app.enable("trust proxy")有快速检查标题自动。 请参阅http://expressjs.com/guide/behind-proxies.html