Node.js 如何配置expressjs以同时处理http和https?
我已经搜索了stackoverflow和ExpressGoogle小组,但我仍然不够 根据我收集的信息,我可以做两件事中的一件: 1) 创建http服务器和https服务器的实例,并将两者设置为侦听两个不同的端口。在路由中,将http请求重定向到https端口Node.js 如何配置expressjs以同时处理http和https?,node.js,express,Node.js,Express,我已经搜索了stackoverflow和ExpressGoogle小组,但我仍然不够 根据我收集的信息,我可以做两件事中的一件: 1) 创建http服务器和https服务器的实例,并将两者设置为侦听两个不同的端口。在路由中,将http请求重定向到https端口 //app var app = express.createServer(); var app_secure = express.createServer({key: key, cert: cert}); app.listen(8080
//app
var app = express.createServer();
var app_secure = express.createServer({key: key, cert: cert});
app.listen(8080);
app_secure.listen(8443);
//routes
app.get("unsecure/path", function(req, res) {
...
}
app.get("secure/path", function(req, res) {
res.redirect("https://domain" + req.path);
}
app_secure.get("secure/path", function(req, res) {
res.send("secure page");
}
2) 照TJ Hollowaychuk说的做:
当我做1时,通常没有问题。然而,管理两台服务器感觉很笨拙,我真的觉得应该有更好的方法
当我做2时,我得到:
(节点SSL)错误:1408A0C1:SSL例程:SSL3\u GET\u CLIENT\u HELLO:没有共享密码
当然,我可以默认选择选项1,但我真的,真的想知道为什么在选择选项2时会出现“无共享密码错误”。选项2是我的首选路线。您的证书是RSA证书而不是DSA证书吗?听起来您的nodejs服务器不支持您的浏览器支持的密码-您需要更新OpenSSL并重新编译nodejs?在@ypocate的评论之后,您可以像这样在express.js应用程序中启用https
var http = require('http');
var https = require('https');
var express = require('express');
var fs = require('fs');
var app = express.createServer();
// cutomize your app as ususal
app.configure( function () { ... });
app.configure('production', function () { ... });
// ....
// attach express handler function to TWO servers, one for http and one for https
http.createServer(app.handle.bind(app)).listen(8080);
https.createServer({
ca: fs.readFileSync('./server.ca-bundle'),
key: fs.readFileSync('./server.key'),
cert: fs.readFileSync('./server.crt')
}, app.handle.bind(app)).listen(8081);
请注意,您应该从证书颁发机构接收server.ca-bundle、server.key和server.crt
另外,由于您可能会在不使用sudo的情况下运行node,您需要确保端口80(http)和443(https)处于打开状态
以及分别在8080至8080和8081至443转发请求
# in Ubuntu
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 8081
希望这有帮助我最终使用Nginx处理SSL@本杰:证书是RSA。我将在不久的将来尝试一下你的建议。谢谢。您能指出您是如何配置nginx来处理node的ssl的吗?谢天谢地的是你没有按照TJ的要点去做——几乎,但不完全是这样。https选项需要转到https服务器,而不是express.createServer。然后它就起作用了。然而,让它与websocket服务器协同工作完全是另一回事:)@Mamsaac抱歉,我没有早点收到你的评论。我记录了我在这里做的事情:。我对这东西还是有点生疏,所以你可以从中吸取教训。我甚至已经忘记了这一点。谢谢:)我做的有点不同,因为我使用nginx进行负载平衡。
# in Ubuntu
sudo ufw status
sudo ufw allow 80
sudo ufw allow 443
# in Ubuntu
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 8081