如何创build一个httpredirectHTTP请求进入端口80到HTTPS端口443?

我想创build一个状态301redirect从像http://whatever.com/whatever?whatever的任何一个url到https://whatever.com/whatever?whatever 。 我使用node.js,但我怀疑答案是特定于节点的。

我知道你可以用这样的url写下“Location”头文件:

response.writeHead(301, { 'Location': request.url }); response.end(); 

但是,如何指定我要redirect到https?

为此常常使用301永久性redirect。 要更改协议,您需要在“ Location标题中包含协议和主机:

 var server = http.createServer(function(request, response){ var newUrl = 'https://' + request.headers.host + request.url; response.writeHead(301, { 'Location': newUrl }); response.end(); }); 

标准的节点HTTP包不会自动parsing主机名和端口,所以如果您需要与非标准端口兼容,您应该使用像Express这样的包来轻松获取req.hostname