1

I am trying to redirect every http request to an https server. This works fine if the port of the https server is the 443. However if I try to redirect to a different port it doesn't happen. Here is my code:

http.createServer(function(req,res){
    var host = req.headers['host'],
        url = req.url;
        res.writeHead(301,
            {"Location": "https://" + host + ":"+SERVER.SPORT + url})
        res.end()
}).listen(SERVER.PORT)

https.createServer(SERVER.HTTPS_OPTIONS,app).listen(SERVER.SPORT)
Community
  • 1
  • 1
Diogo Almiro
  • 363
  • 3
  • 15

1 Answers1

2

Your host most likely already includes the port number.

You can make sure if you change this:

var host = req.headers['host']

to:

var host = req.headers['host'].split(':')[0];

Also add some logging:

console.log("https://" + host + ":"+SERVER.SPORT + url);

to see what the URL that you're building looks like.

You can also want to use the url module to work with URLs instead of manually concatenating strings to avoid mistakes like that. See:

In any case add some logging to know what the URL that you're building looks like. Also test it with curl:

curl -v http://localhost:1234

to see what headers are returned.

rsp
  • 107,747
  • 29
  • 201
  • 177
  • I had that in a log and didn't notice. I felt really dumb after your answer they even have a nice representation of the url in the [api](https://nodejs.org/api/url.html#url_url_strings_and_url_objects)! But If I explicitly asked for the `example.com:80` the method found in other answers (and that I used) would also fail. Which means that this only works because of the hidden default ports? – Diogo Almiro Feb 10 '17 at 20:10