2015-10-05 94 views
9

我有一個簡單的Express.js實例,它爲單個頁面Angular應用程序提供靜態資產。我在Express配置中設置了一些中間件,以便爲所有路由返回index.html,並且可以從那裏加載Angular。Express.js重定向到HTTPS併發送index.html

最近,我在Heroku上設置了SSL,我想確保所有來自HTTP的流量都被重定向到HTTPS。我試圖將來自this post的建議解決方案與我現在擁有的解決方案結合起來,但最終會陷入無盡的重定向循環。

簡而言之,我需要將所有流量從HTTP重定向到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); 

回答

16

Heroku的終止在負載均衡水平SSL連接,所以req.secure絕不會因爲你對Heroku的負載均衡器連接不使用SSL,從而創造無限重定向循環是真實的。

你必須檢查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

+0

太棒了,這似乎爲我工作。我在這裏唯一的另一個問題是,它不會在根上應用重定向,只能在其他路由上應用。我試着把'''app.all'''改成'''app.use(ensureSecure);'''沒有運氣。有關於此的任何想法? –

+0

@WillHitchcock是的,我打算建議使用app.use而不是app.all,但不確定如果這不起作用,問題是什麼。嘗試添加更多的日誌來跟蹤在這種情況下發生的情況。 – Philippe

+1

我想我明白了。我只需要在'''app.use(gzippo ...'''line'之前加入重定向。立即工作! –