【发布时间】:2017-02-28 23:21:20
【问题描述】:
我有一个在 AWS Windows 和 Node.js 上运行的应用程序。我可以使用 http 和 https 访问。但是如果有人通过 http 访问,我需要它将 http 转发到 https。 我可以想出很多方法,但如果对最佳方法有任何建议,我将不胜感激。服务器是一个 EC2 实例,通过负载均衡器访问。
【问题讨论】:
标签: node.js http amazon-ec2 https window
我有一个在 AWS Windows 和 Node.js 上运行的应用程序。我可以使用 http 和 https 访问。但是如果有人通过 http 访问,我需要它将 http 转发到 https。 我可以想出很多方法,但如果对最佳方法有任何建议,我将不胜感激。服务器是一个 EC2 实例,通过负载均衡器访问。
【问题讨论】:
标签: node.js http amazon-ec2 https window
如果您使用的是 express,这个中间件模块可以很容易地强制执行 https:https://www.npmjs.com/package/express-force-ssl
如果您在应用程序(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');
}
});
【讨论】:
node app.js 运行