gpt4 book ai didi

redirect - Heroku Node JS http 到 https ssl 强制重定向

转载 作者:IT老高 更新时间:2023-10-28 21:47:34 29 4
gpt4 key购买 nike

我有一个应用程序在 Heroku 上使用 Express.js 在 Node.js 上使用 https 启动并运行。如何识别协议(protocol)以在 Heroku 上使用 Node.js 强制重定向到 https

我的应用程序只是一个简单的 http-服务器,它(还)没有意识到 Heroku 正在发送它 https-requests:

// Heroku provides the port they want you on in this environment variable (hint: it's not 80)
app.listen(process.env.PORT || 3000);

最佳答案

截至今天,2014 年 10 月 10 日,使用 Heroku Cedar 堆栈ExpressJS ~3.4.4,这是一组工作代码。

这里要记住的主要事情是我们正在部署到 Heroku。 SSL 终止发生在负载均衡器上,在加密流量到达您的 Node 应用程序之前。可以通过 req.headers['x-forwarded-proto'] === 'https' 测试是否使用 https 发出请求。

如果您在其他环境中托管,我们无需担心在应用程序等中拥有本地 SSL 证书。但是,如果使用您自己的证书、子域等,您应该首先通过 Heroku 插件应用 SSL 插件。

然后只需添加以下内容即可将 HTTPS 以外的任何内容重定向到 HTTPS。这与上面接受的答案非常接近,但是:

  1. Ensures you use "app.use" (for all actions, not just get)
  2. Explicitly externalises the forceSsl logic into a declared function
  3. Does not use '*' with "app.use" - this actually failed when Itested it.
  4. Here, I only want SSL in production. (Change as suits your needs)

代码:

 var express = require('express'),
env = process.env.NODE_ENV || 'development';

var forceSsl = function (req, res, next) {
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect(['https://', req.get('Host'), req.url].join(''));
}
return next();
};

app.configure(function () {
if (env === 'production') {
app.use(forceSsl);
}

// other configurations etc for express go here...
});

SailsJS (0.10.x) 用户注意事项。您可以在 api/policies 中简单地创建一个策略 (enforceSsl.js):

module.exports = function (req, res, next) {
'use strict';
if ((req.headers['x-forwarded-proto'] !== 'https') && (process.env.NODE_ENV === 'production')) {
return res.redirect([
'https://',
req.get('Host'),
req.url
].join(''));
} else {
next();
}
};

然后引用 config/policies.js 以及任何其他策略,例如:

'*': ['authenticated', 'enforceSsl']

关于redirect - Heroku Node JS http 到 https ssl 强制重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7185074/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com