Node.js: Redirecting port 80 to port 443

When you’re setting up a server, there’s a common pattern in Node you might want to know about when deciding how to expose your ports and route traffic.

In general, we only want secure traffic that goes over port 443. But clients can often make the mistake of requesting that same resource at port 80, and so what do we do?

The answer is a simple redirect. Here’s what the boilerplate of that server code looks like:

var https = require('https');

var fs = require('fs');
var options = {
    key: fs.readFileSync('./key.pem'),
    cert: fs.readFileSync('./cert.pem')

https.createServer(options, function (req, res) {
    res.end('Listening on 443');

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url });

So we’ve got two servers, but one is just a redirect.

Let's get started

Just let us know the basics and we'll send you a Slack invite to discuss with the whole team.

What are we going to be talking about?

%d bloggers like this: