How to force HTTPS behind an Amazon Web Services Elastic Load Balancer

Recently I have been learning the Amazon Web Services (AWS) platform and have created a setup with two web servers running NGINX and PHP behind an Elastic Load Balancer (ELB). Later I added HTTPS support and I came across an issue where HTTPS requests were getting redirected to HTTP. Luckily the ELB supports the HTTP header X-FORWARDED-PROTO and using a simple rewrite rule, HTTPS can be enforced. To serve as a reference for myself and to help others out, below is the code required to achieve this on the most popular HTTP server software:




Note: When configuring the ELB health check, it is important to configure this to check HTTP on port 80 (assuming SSL terminates at the ELB).