0
我有一個在AWS Windows和Node.js上運行的應用程序。我可以使用http和https訪問。但是如果有人通過http訪問,我需要它將http轉發給https。 我能想到很多方法,但會感謝任何有關最佳方法的建議。服務器是一個EC2實例,通過負載均衡器訪問。將HTTP轉發到HTTPS - AWS Windows Node.js
我有一個在AWS Windows和Node.js上運行的應用程序。我可以使用http和https訪問。但是如果有人通過http訪問,我需要它將http轉發給https。 我能想到很多方法,但會感謝任何有關最佳方法的建議。服務器是一個EC2實例,通過負載均衡器訪問。將HTTP轉發到HTTPS - AWS Windows Node.js
如果您使用快遞,這個中間件模塊可以很容易地執行HTTPS:如果你在你的應用程序(ELB,nginx的,等等)的前使用反向代理https://www.npmjs.com/package/express-force-ssl
,你會需要設置信任代理設置。
這裏是沒有上述模塊的樣品:
// Forward all requests to HTTPS.
// enable reverse proxy support in Express. This causes the
// the "X-Forwarded-Proto" header field to be trusted so its
// value can be used to determine the protocol. See
// http://expressjs.com/api#app-settings for more details.
app.enable('trust proxy');
// Add a handler to inspect the req.secure flag (see
// http://expressjs.com/api#req.secure). This allows us
// to know whether the request was via http or https.
app.use((req, res, next) => {
if (req.secure) {
// request was via https, so do no special handling
next();
} else {
// request was via http, so redirect to https
console.log('Redirecting to https');
res.redirect('https://' + req.headers.host + req.url);
}
});
完整的示例app.js
var express = require('express');
var app = express();
// Forward all requests to HTTPS.
// enable reverse proxy support in Express. This causes the
// the "X-Forwarded-Proto" header field to be trusted so its
// value can be used to determine the protocol. See
// http://expressjs.com/api#app-settings for more details.
app.enable('trust proxy');
// Add a handler to inspect the req.secure flag (see
// http://expressjs.com/api#req.secure). This allows us
// to know whether the request was via http or https.
app.use((req, res, next) => {
if (req.secure) {
// request was via https, so do no special handling
next();
} else {
// request was via http, so redirect to https
console.log('Redirecting to https');
res.redirect('https://' + req.headers.host + req.url);
}
});
// Respond to any GET requests with our message
app.get('*', (req, res) => {
res.send('This is only served over https');
});
// Listen on the assigned port
var port = process.env.PORT || 3001;
app.listen(port);
console.log('Hello started on port ' + port);
重定向只有GET請求,與錯誤應對非GET請求
app.all('*', (req, res, next) => {
if (req.secure) {
next();
} else if (req.method === 'GET') {
res.redirect(`https://${req.headers.host}${req.url}`);
} else {
res.status(401).send('Secure channel required');
}
});
謝謝,這看起來非常接近我所追求的。目前我收到「發送後無法設置標題」。我一直試圖進一步把代碼,但後來我得到「無法讀取屬性」啓用「未定義」。對不起,我是一個相當新的節點:-) –
我在上面的答案中添加了一個完整的示例應用程序。保存爲app.js然後運行''node app.js'' – bsyk
它工作線majic,我不得不在重定向前添加「返回」..多數民衆贊成在所有。謝謝 –