When running a server on a non-standard port, there's a chance of a client incorrectly using HTTP instead of HTTPS.
I would like to return an HTTP 301 redirect if that's detected.
NodeJS does raise a helpful error in that case, but writing a response in that error handler doesn't go through to the client (I believe the socket is already destroyed at that point).
const https = require('https');
const fs = require('fs');
const port = 9000;
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
server = https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(port);
server.on('clientError', (err, conn) => {
if (err.code == "ERR_SSL_HTTP_REQUEST") {
console.warn("HTTP request was sent to HTTPS port");
conn.end('HTTP/1.1 301 Moved Permanently\r\nLocation: https://127.0.0.1:8443')
}
});
Sending an HTTP request with curl -v http://127.0.0.1:9000
just gives Empty reply from server
.
As an interesting aside. The error code ERR_SSL_HTTP_REQUEST
appears in zero Google Search results. Anyone know how that code gets generated?