重定向到HTTPS使用不同的端口而不是默认
问题描述:
这里是Node.js的一个例子:重定向到HTTPS使用不同的端口而不是默认
var https = require("https");
var fs = require("fs");
var options = {
key: fs.readFileSync("/tmp/key.pem"),
cert: fs.readFileSync("/tmp/cert.pem")
};
https.createServer(options, function(req, res) {
res.end("secure!");
}).listen(4430);
var http = require("http");
http.createServer(function(req,res) {
console.log(req);
res.writeHead(301, {"location": "https://" + req.headers["host"] + req.url});
res.end("not secure!");
}).listen(8001);
会重定向到http://localhost:8001https://localhost:8001,这个问题是HTTPS服务器监听4430我该如何解决这个?
答
好吧,只需要一点点的字符串操作。而不是req.headers["host"]
,请使用req.headers["host"].split(":")[0]
。
这不工作? 'res.writeHead(301,{“location”:“https://”+ req.headers [“host”] +':4430'+ req.url});' –
不,这会产生一个无效的url: 'https:// localhost:3000:4430 /' – qed
啊对。那么,res.writeHead(301,{“location”:“https://”+ req.headers [“host”]。replace(“:8001”,“:4430”)+ req.url})怎么样?) ;'? –