gpt4 book ai didi

node.js - 使用 node.js/express 自动 HTTPS 连接/重定向

转载 作者:IT老高 更新时间:2023-10-28 21:46:07 25 4
gpt4 key购买 nike

我一直在尝试使用我正在处理的 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。

如何让 Node (以及我正在使用的框架中的 Express)将所有传入流量移交给 https,无论是否指定它?我无法找到任何解决此问题的文档。还是只是假设在生产环境中,node 前面有一些东西(例如 nginx)来处理这种重定向?

这是我第一次涉足网络开发,如果这是显而易见的事情,请原谅我的无知。

最佳答案

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

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

// 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 规则,以便 Node 不必以 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

总的来说,这完全符合我的要求。

要防止通过 HTTP 窃取 cookie,请参阅 this answer (来自评论)或使用此代码:

const session = require('cookie-session');
app.use(
session({
secret: "some secret",
httpOnly: true, // Don't let browser javascript access cookies.
secure: true, // Only use cookies over https.
})
);

关于node.js - 使用 node.js/express 自动 HTTPS 连接/重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7450940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com