I recently worked on a project utilizing Heroku as a hosting platform. A significant concern for this application was to force the user to always use HTTPS when browsing the website. Setting this up in a simple Express web app on Heroku means we intercept the request, check the protocol used and force HTTPS if it is not already using it.

1
2
3
4
5
6
7
8
9
10
11
12
app.use(function (req, res, next) {
  var sslUrl;

  if (process.env.NODE_ENV === 'production' &&
    req.headers['x-forwarded-proto'] !== 'https') {

    sslUrl = ['https://hjnilsson.com', req.url].join('');
    return res.redirect(sslUrl);
  }

  return next();
});

So if the user visits the site using HTTP. They will immediately get a 302 redirect to the HTTPS version of the site. Excellent!

However, we also have aliases for our website, and we for example nttlssonhj.com to redirect to hjnilsson.com. We can accomplish this by looking at the host field as well, and redirecting if it is not HTTPS, or if it is not on the correct domain:

1
2
3
4
5
6
7
8
9
10
11
12
13
app.use(function (req, res, next) {
  var newURL;

  // If not on HTTPS, or not on the main domain, redirect
  if (process.env.NODE_ENV === 'production' &&
    (req.headers['x-forwarded-proto'] !== 'https' || req.headers.host !== 'hjnilsson.com')) {

    newURL = ['https://hjnilsson.com', req.url].join('');
    return res.redirect(newURL);
  }

  return next();
});

This solves the issue, and no matter what domain alias you use to visit the site (including hjnilsson.herokuapp.com), it will redirect to your main domain. As you want it to do.