I am using the solution provided by Basarat, but I also need to reload the port because I had two different ports for the HTTP and HTTPS protocols.
res.writeHead(301, { "Location": "https://" + req.headers['host'].replace(http_port,https_port) + req.url });
I also prefer to use a non-standard port to start nodejs without root privileges. I like 8080 and 8443 becaouse I come from many years of tomcat programming.
My full file will become
var fs = require('fs'); var http = require('http'); var http_port = process.env.PORT || 8080; var app = require('express')(); // HTTPS definitions var https = require('https'); var https_port = process.env.PORT_HTTPS || 8443; var options = { key : fs.readFileSync('server.key'), cert : fs.readFileSync('server.crt') }; app.get('/', function (req, res) { res.send('Hello World!'); }); https.createServer(options, app).listen(https_port, function () { console.log('Magic happens on port ' + https_port); }); // Redirect from http port to https http.createServer(function (req, res) { res.writeHead(301, { "Location": "https://" + req.headers['host'].replace(http_port,https_port) + req.url }); console.log("http request, will go to >> "); console.log("https://" + req.headers['host'].replace(http_port,https_port) + req.url ); res.end(); }).listen(http_port);
Then I use iptable to format 80 and 443 traffic on my HTTP and HTTPS ports.
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp
Lorenzo Eccher Oct. 20 '17 at 15:24 2017-10-20 15:24
source share