ExpressJS ~3.4.4,以下是一组可工作的代码。
这里要记住的主要事情是我们正在部署到Heroku。 SSL终止发生在负载均衡器处,在加密流量到达您的节点应用程序之前。可以使用req.headers ['x-forwarded-proto'] ==='https'测试是否使用https进行请求。
我们不需要担心在应用程序中有本地SSL证书等问题,如果在其他环境中进行托管,则可能需要。但是,如果使用自己的证书、子域等,则应首先通过Heroku Add-ons应用SSL附加组件。
然后,只需添加以下内容即可将任何非HTTPS重定向到HTTPS。
- 确保使用“app.use”(对于所有操作,而不仅仅是获取)
- 明确将forceSsl逻辑外部化为已声明的函数
- 不要在“app.use”与“*”一起使用-当我测试时,这实际上失败了。
- 这里,我只想在生产中使用SSL。(根据需要更改)
代码:
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);
}
});
注意针对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']
app.get('*',function(req,res,next){ if(req.headers['x-forwarded-proto']!='https') res.redirect('https://mypreferreddomain.com'+req.url) else next() })
- Derek Bredensteiner