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

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

问题描述

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

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

我想弄清楚如何强制所有连接都通过 https.

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

Google 搜索显示了这个:

Google searching shows me this:

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

目前没有办法强制 https 重定向,尽管看起来就像有点奇怪的解决方法.我们有一个仅限 https 的应用程序,我们只需要一个简单的 ~4 行节点 http 服务器来重定向,什么都没有花哨的

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

这是我需要的,但他没有说那 4 行是什么.

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();
});

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

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.

如果您的应用在 Nginx 等其他服务器之后运行,您可能需要添加配置参数 app.set('trust proxy', true).或者,更好的是,让 Nginx 自己做重定向,这将比任何 Node.js 应用程序都更有效率.

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.

根据我的基准,join 在连接字符串方面比 + 快一点.没什么戏剧性的,但每次胜利都是胜利......

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

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

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