2015-07-11 28 views
0

這裏是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我該如何解決這個?

+0

這不工作? 'res.writeHead(301,{「location」:「https://」+ req.headers [「host」] +':4430'+ req.url});' –

+0

不,這會產生一個無效的url: 'https:// localhost:3000:4430 /' – qed

+0

啊對。那麼,res.writeHead(301,{「location」:「https://」+ req.headers [「host」]。replace(「:8001」,「:4430」)+ req.url})怎麼樣?) ;'? –

回答

0

好吧,只需要一點點的字符串操作。而不是req.headers["host"],請使用req.headers["host"].split(":")[0]

相關問題