使用node.js / express自动HTTPS连接/重定向 [英] Automatic HTTPS connection/redirect with node.js/express

查看:437
本文介绍了使用node.js / express自动HTTPS连接/重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用正在处理的node.js项目设置HTTPS。我已经基本遵循了 node.js文档的示例:

I've been trying to get HTTPS set up with a node.js project I'm working on. I've essentially followed the node.js documentation for this example:

// curl -k https://localhost:8000/
var https = require('https');
var fs = require('fs');

var options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(8000);

现在,当我做

curl -k https://localhost:8000/

hello world

如预期。但是如果我这样做的话,你可以在

as expected. But if I do

curl -k http://localhost:8000/

我得到

curl: (52) Empty reply from server

回想起来,这显然可以这样工作,但同时,最终访问我的项目的人将不会输入 https :// yadayada,并且我希望所有流量都从https到达网站。

In retrospect this seems obvious that it would work this way, but at the same time, people who eventually visit my project aren't going to type in https://yadayada, and I want all traffic to be https from the moment they hit the site.

如何获取节点(和Express,因为我正在使用的框架)将所有传入流量切换到https,无论是否指定?我没有找到任何解决这个问题的文件。或者只是假设在生产环境中,节点有一些位于它前面的东西(例如nginx)来处理这种重定向?

How can I get node (and Express as that is the framework I'm using) to hand off all incoming traffic to https, regardless of whether or not it was specified? I haven't been able to find any documentation that has addressed this. Or is it just assumed that in a production environment, node has something that sits in front of it (e.g. nginx) that handles this kind of redirection?

这是我的第一个进入网络开发,所以请原谅我的无知,如果这是明显的。

This is my first foray into web development, so please forgive my ignorance if this is something obvious.

推荐答案

Ryan,谢谢指出我在右边方向。我用一些代码丰富了你的答案(第2段),它的工作原理。在这种情况下,这些代码片段放在我的快速应用程序中:

Ryan, thanks for pointing me in the right direction. I fleshed out your answer (2nd paragraph) a little bit with some code and it works. In this scenario these code snippets are put in my express app:

// set up plain http server
var http = express.createServer();

// set up a route to redirect http to https
http.get('*',function(req,res){  
    res.redirect('https://mydomain.com'+req.url)
})

// have it listen on 8080
http.listen(8080);

https快速服务器在3000上侦听ATM。我设置了这些iptables规则,以便节点不必须以root身份运行:

The https express server listens ATM on 3000. I set up these iptables rules so that node doesn't have to run as root:

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 3000

所有这些都与我想要的一样工作。

All together, this works exactly as I wanted it to.

这篇关于使用node.js / express自动HTTPS连接/重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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