我一直在尝试通过正在处理的node.js项目来设置HTTPS。对于此示例,我基本上遵循node.js documentation

// 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


如预期的那样。但是如果我这样做

curl -k http://localhost:8000/


我懂了

curl: (52) Empty reply from server


回想起来,这样做似乎很明显,但是与此同时,最终访问我项目的人不会输入https:// yadayada,我希望从点击起就将所有流量都设为https网站。

我如何获得节点(以及Express,因为我正在使用的框架)将所有传入流量传递给https,而不管是否指定了它?我还没有找到解决此问题的任何文档。还是只是假设在生产环境中,节点位于它前面的东西(例如nginx)可以处理这种重定向?

这是我第一次涉足Web开发,所以如果这很明显,请原谅我的无知。

最佳答案

瑞安(Ryan),感谢您为我指明了正确的方向。我用一些代码充实了您的答案(第二段),它可以工作。在这种情况下,这些代码段被放入我的快速应用程序中:

// 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://' + req.headers.host + req.url);

    // Or, if you don't want to automatically detect the domain name from the request header, you can hard code it:
    // res.redirect('https://example.com' + req.url);
})

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


https express服务器在3000上侦听ATM。我设置了这些iptables规则,因此节点不必以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


总之,这完全符合我的期望。

10-08 03:16