How to redirect to HTTPS from Angular+Node app hosted in Heroku from a subdomain?

350 Views Asked by At

Been struggling with this for a couple of day now. I have an Angular 9 app, a subdomain (subdomain.side.com) and a Heroku app running Nodejs server. Heroku app has SSL and is connected correctly to the domain panel via DNS, also heroku is running a simple server to start the app.

Problem

I want to redirect user to the HTTPS of my subdomain, for instance if user types http://subdomain.side.com it will be redirected to the HTTPS site (https://subdomain.side.com).

Attempts

  1. Added the .htaccess file. Also added it to the prod folder as well.
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  1. Configures with a lot of different setups the server.js file the latest is:
const express = require('express');
const compression = require('compression');
const path = require('path');
const app = express();
app.use(compression());
app.use(express.static(__dirname + '/dist/APP'));

function ensureSecure(req, res, next) {
  if (req.headers['x-forwarded-proto'] === 'https') {
    return next();
  }
  res.redirect('https://' + req.hostname + req.url);
}

app.all('*', ensureSecure);
app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname + '/dist/APP/index.html'));
});
app.listen(process.env.PORT || 8080);
1

There are 1 best solutions below

0
On

Not the prettiest solution but a workaround if somebody is struggling with the same issue. I added a guard to the root route checking if the page is not HTTPS then redirect it to HTTPS, not ideal but...

  if (location.protocol === 'http:') {
      window.location.href = location.href.replace('http', 'https');
   }