HTTPS NodeJS和Heroku。 强制HTTPS?

我有一个在Heroku上运行的NodeJS HTTP(非S)服务器。 我configuration了SSL,并接受对HTTPS的请求。 我使用香草HTTP服务器的原因是因为以下原因 :

SSL termination occurs at Heroku's load balancers; they send your app plain (non-SSL) traffic, so your app should create a non-HTTPS server." 

不幸的是,我的应用程序仍然响应简单的HTTP请求。 我想强制redirect或从HTTP到HTTPS的东西。 我可以用一些中间件来做到这一点:

 /* At the top, with other redirect methods before other routes */ app.get('*',function(req,res,next){ if(req.headers['x-forwarded-proto']!='https') res.redirect('https://mypreferreddomain.com'+req.url) else next() /* Continue to other routes if we're not redirecting */ }) 

但这是一个很好的解决scheme吗? POST请求如何工作? 如果我张贴到HTTP,应该允许吗?

我在想的另一个最后的方法是使用Nginx,并在那里从HTTPredirect到HTTPS。 不幸的是Heroku不允许Nginx的configuration。

更好地使用app.use(function(req, res, next{ /* ... */ });来捕获其他的HTTP方法。

所以假设你把它放在你的中间件链的最前面,在路由器本身之前,这应该是非常高效的。

但是,让我们把它放在一个档次。 假设你在多个环境中部署了这个服务器,而不仅仅是Heroku,那么如果你希望协调多个环境的行为,那么你就很难避免在中间件中进行一些有条件的包含或者在它内部进行常量条件分支。

如果你为Heroku编写一个特定的服务器,你可以跳过所有这些:

 var app = require('./app').createApp(); var server = require('http').createServer(function (req, res) { if (!secure(req)) { // Redirect res.statusCode = 302; res.setHeader('Location', pathname); res.setHeader('Content-Length', '0'); res.end(); } else { app.handle(req, res); } }); server.listen(80); 

此外,请尽量避免手动构buildurl。 你应该真的尝试使用URL库,特别是url.parse()url.resolve()函数,因为parsing和构造URL是非平凡的(考虑隐式/显式尾随斜线,散列,查询和URL编码) 。

这是一个小的预览:

 var url = require('url'); url.parse('http://www.foo.com?bar=baz#quux') { protocol: 'http:', slashes: true, auth: null, host: 'www.foo.com', port: null, hostname: 'www.foo.com', hash: '#quux', search: '?bar=baz', query: 'bar=baz', pathname: '/', path: '/?bar=baz', href: 'http://www.foo.com/?bar=baz#quux' }