How do you get RequireSSL in NodeJS on an Azure Website?

127 views Asked by At

So a little background first: A NodeJS server running in an Azure Website will automatically have all HTTPS requests directed to the http endpoint. This allows the following code to work for both HTTP and HTTPS

var http = require('http');
var express = require('express');

var app = express();
// *snip*
http.createServer(app).listen(process.env.PORT);
// can go to http://*.azurewebsites.net or https://*.azurewebsites.net without issue

From here I decided to create a "RequireSSL" middleware

/* snip */
if (req.protocol === 'http') {
    var origFullUrl: string = 'http://' + req.get('host') + req.originalUrl;
    var u: url.Url = url.parse(origFullUrl, true);
    u.host = null; // nead to clear so 'port' is used
    u.protocol = 'https';
    u.port = '443';

    res.redirect(url.format(u));
}
/* snip */

Here's where the background comes into play. Because Azure redirects all HTTPS to the HTTP protocol the req.protocol always equals 'http' creating a redirect loop.

Anyone know of a way to get this to work in an Azure Website?

1

There are 1 answers

0
Ranjith Ramachandra On BEST ANSWER

You can detect this using x-arr-ssl header.. Please go through this : https://coderead.wordpress.com/2014/09/05/redirecting-to-https-in-node-js-on-azure-websites/