Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Req.secure in Node alwys false

Im trying to redirect HTTP requests to my site to HTTPS. Its been extraordinarily hard. My code is:

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


app.use(function(req, res, next) {

  console.log('req.protocol is ', req.protocol);
  console.log('req.secure is ', req.secure);


  if (req.url !== '/health' && !req.secure) {
    console.log('redirecting .........');
    return res.redirect('https://www.example.net/catch');

  }
  next();
});


app.get('/catch', function(req, res) {
  res.send('Hello World!');
});

app.get('/', function(req, res) {
  res.send('Hello World!');
});

app.get('/health', function(req, res) {
  res.send('Hello World!');
});


app.listen(8080, function() {
  console.log('Example app listening on port 8080!');
});

The load Balancer health check goes to '/health'. Every other request that isnt a health check, and is HTTP (rather than HTTPS) should be caught and redirected to https. However, I end up in an infinite loop as req.protocol always returns 'http' for http or https requests. req.secure therefore is false every time and I end up in a loop. Any ideas why this is?

like image 812
Mark Avatar asked Dec 30 '25 05:12

Mark


1 Answers

It sounds like you installed the SSL certificate on your Elastic Load Balancer, so that's where SSL Termination is happening. So your load balancer is doing the SSL termination and always communicating with your server via HTTP. This means you have to check the 'x-forwarded-proto' header to determine if the original request is over HTTPS.

There are several other ways to configure SSL on AWS, including termination on the web server, but SSL termination on the ELB is the generally preferred method on AWS. You just have to be aware that in this configuration the request between the ELB and the web server isn't actually over SSL so you have to check the header accordingly.

like image 51
Mark B Avatar answered Jan 01 '26 20:01

Mark B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!