// If no need to forcibly redirect HTTP requests to same path HTTPS route. if (!httpsConfig.forceHttpsWhenEnabled) { // OK. Normal flow. return https.createServer(options, handler); }
/** * Automatically redirect http request to https. * Only change the protocol. * @see https://stackoverflow.com/a/42019773 */ const net = require('net'); const server = net.createServer(conn => { conn.once('data', buffer => { // Pause the socket. conn.pause();
const proxy = server[protocol]; if (proxy) { // Push the buffer back onto the front of the data stream. conn.unshift(buffer); // Emit the socket to the HTTP(s) server. proxy.emit('connection', conn); }
// As of NodeJS 10.x the socket must be // resumed asynchronously or the socket // connection hangs, potentially crashing // the process. Prior to NodeJS 10.x // the socket may be resumed synchronously. process.nextTick(() => { conn.resume(); }); }); });
// HTTP server proxy. server.http = http.createServer((req, res) => { // Force redirect. const host = req.headers['host']; // Use 301 - Moved Permanently. // To notify browsers that update the bookmarks and cache the redirection. res.writeHead(301, { Location: 'https://' + host + req.url }); res.end(); });
// HTTPS server proxy. server.https = https.createServer(options, handler);