I am using the following to redirect all http requests to https requests.
I can see from logs that the header 'x-forwarded-proto' is never populated and is undefined.
app.get('*', function(req, res, next) {
//http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#x-forwarded-proto
if (req.headers['x-forwarded-proto'] != "https") {
res.redirect('https://' + req.get('host') + req.url);
} else {
next();
}
});
It is causing a redirect loop. How can I redirect properly without looping?
edit: my original answer below is for express 3.x, for 4.x you can get a string
http
orhttps
inreq.protocol
, thx @BrandonClarkuse
req.get
, notreq.headers
. Note that POST requests and all other non-GET will not see this middleware. It's also possible that Express does not carry thex-forwarded-proto
header across when you redirect. You may need to set it yourself.Another way to force https:
You can edit the nginx config file in the EC2 instance. SSH to ec2 instance and follow the following steps
/etc/nginx/conf.d
00_elastic_beanstalk_proxy.conf
sudo vi 00_elastic_beanstalk_proxy.conf
put
location / { if ($http_x_forwarded_proto != 'https') { rewrite ^ https://$host$request_uri? permanent; } … }
reload nginx
sudo /usr/sbin/nginx -s reload