强制SSL with expressjs 3 [英] Force SSL with expressjs 3

查看:113
本文介绍了强制SSL with expressjs 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个没有代理和使用SSL的node.js express 3服务器。



我试图找出如何强制所有连接去通过https。



Google搜索显示我:



https://groups.google.com/forum/#!topic/express-js/Bm6yozgoDSY


目前还没有办法强制使用https重定向,尽管这似乎是一些奇怪的解决方案。我们有一个只有https的应用程序,我们
只有一个简单的〜4行节点http服务器重定向,没有
花式


我需要什么,但他不说这4行是什么。



我们该怎么做?谢谢。

解决方案

我不太明白启动两台服务器的时候,只有一个人才能完成这项工作。例如,通过在您的服务器文件中添加一个简单的中间件:

  app.use(function(req,res,next){ 
if(!req.secure){
return res.redirect(['https://',req.get('Host'),req.url] .join(''));
}
next();
});

这将重定向任何非安全请求到相应的HTTPS页面。例如, http://example.com/ https://example.com/ http://example.com/foo?bar=woo https://example.com/foo?bar=woo 。这绝对是我期望的行为。也许你应该过滤这个主机,所以它只重定向到您拥有的域,并安装了正确的证书。



如果你的应用程序运行在另外一个服务器像Nginx,您可能需要添加配置参数 app.set('trust proxy',true)。或者,更好的是,使Nginx执行重定向本身,这将比任何Node.js应用程序更有效。



编辑:根据我的基准,加入比连接字符串的 + 要快一些。没有什么戏剧性,但每场胜利都是一场胜利。


I'm running a node.js express 3 server with no proxies and using SSL.

I'm trying to figure out how to force all connections to go through https.

Google searching shows me this:

https://groups.google.com/forum/#!topic/express-js/Bm6yozgoDSY

There's currently no way to force https redirects, though that seems like a bit of a strange work-around. We have an https-only app and we just have a simple ~4 line node http server that redirects, nothing fancy

Which is what I need, but he doesn't say what those 4 lines are.

How do we do this? Thanks.

解决方案

I don't really understand the point in starting two servers when only one can do the job perfectly. For example, by adding a simple middleware in your server file:

app.use(function(req, res, next) {
  if(!req.secure) {
    return res.redirect(['https://', req.get('Host'), req.url].join(''));
  }
  next();
});

This will redirect any non-secure request to the corresponding HTTPS page. For example, http://example.com/ to https://example.com/ and http://example.com/foo?bar=woo to https://example.com/foo?bar=woo. This is definitely the behavior I would expect. Maybe you should filter this by host, so it redirects only on domains for which you own and installed a proper certificate.

If your app is running behind another server like Nginx, you may want to add the configuration parameter app.set('trust proxy', true). Or, even better, make Nginx do the redirect itself, which will be more efficient than any Node.js app.

Edit: According to my benchmarks, join is a little faster than + for concatenating strings. Nothing dramatic, but every win is a win...

这篇关于强制SSL with expressjs 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆