将HTTP转发到HTTPS-AWS Windows Node.js
我有一个在AWS Windows和Node.js上运行的应用程序。我可以使用http和https进行访问。但如果有人通过http访问,我需要它将http转发到https。将HTTP转发到HTTPS-AWS Windows Node.js,node.js,http,amazon-ec2,https,window,Node.js,Http,Amazon Ec2,Https,Window,我有一个在AWS Windows和Node.js上运行的应用程序。我可以使用http和https进行访问。但如果有人通过http访问,我需要它将http转发到https。 我可以想出很多办法,但如果您能给我提供最好的建议,我将不胜感激。服务器是一个EC2实例,通过负载平衡器访问。如果您使用的是express,此中间件模块可以轻松实施https: 如果您在应用程序(ELB、nginx等)前面使用反向代理,则需要设置信任代理设置 以下是一个没有上述模块的示例: // Forward all
我可以想出很多办法,但如果您能给我提供最好的建议,我将不胜感激。服务器是一个EC2实例,通过负载平衡器访问。如果您使用的是express,此中间件模块可以轻松实施https: 如果您在应用程序(ELB、nginx等)前面使用反向代理,则需要设置信任代理设置 以下是一个没有上述模块的示例:
// 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');
}
});
谢谢,这看起来很接近我想要的。目前我得到“发送后无法设置标题”。我一直试图把代码放得更高一些,但是我得到了“无法读取未定义的属性'enable'”。很抱歉,我是一个新的节点:-)我已经在上面的答案中添加了一个完整的示例应用程序。将其另存为app.js,然后使用
节点app.js运行
行majic,我必须在重定向前添加“return”。。就这些。谢谢我应该补充一点,重定向非GET请求不是一个好主意。如果一个POST呼叫进入并被重定向,浏览器会将该重定向呼叫作为GET。您可能希望使用401或类似的非GET请求进行响应。你可以像上面那样做。太棒了。工作起来很有魅力。:)当我的EC2 node.js服务器位于ELB后面时,它特别有用。