Expressjs redirects to https (using Cloudflare Flexible SSL)

im using Expressjs (NodeJS framework) and I want to redirect all traffic to https im not using SSL certificates but Cloudflare flexible ssl.

I am using this middleware:

//FORCE SSL
app.use(function(req, res, next) {
  if(!req.secure) {
    return res.redirect(['https://', req.get('Host'), req.url].join(''));
  }
  next();
});

      

And I run my application this way:

//Firing Up express
//====================================================================
app.set('port', process.env.PORT || 80);
var server = app.listen(app.get('port'), function() {
   console.log('[-]');
   console.log(('[+] Express server listening on port '+ server.address().port).green);
   console.log('[-]');
});

      

Application redirects to https: // but then fails to load

Google Chrome console says:

Failed to load resource: net::ERR_CONNECTION_REFUSED https://beta.domain.io/
Failed to load resource: net::ERR_CONNECTION_CLOSED https://beta.domain.io/
Failed to load resource: net::ERR_CACHE_MISS 

      

Can anyone point me in the right direction?

Thanks in advance.

+3


source to share


1 answer


CloudFlare server is actually talking to your server over insecure http. It then redirects the response to the client via https. Since all connections to your server are http, your application redirects everything. In this case, there will never be a valid response and therefore will not load.

When a proxy server connects to your web server, it conveys additional client connection information via HTTP headers. There are two headings you should be looking for. X-Forwarded-For and X-Forwarded-Proto. X-Forwarded-For will tell you what the original client IP is and X-Forwarded-Proto will tell you which protocol the original client is using.



In your case, you want to look at the X-Forwarded-Proto header, and if it is http

, then redirect it to an equivalent resource https

.

//FORCE SSL
app.use(function(req, res, next) {
  if(req.headers['x-forwarded-proto']==='http') {
    return res.redirect('https://' + req.headers.host + req.url);
  }
  next();
});

      

+5


source







All Articles