apache HTTP:X-Forwarded-Proto in .htaccess is causing redirect loop in dev environment

RegexAmazon Web-ServicesApache.HtaccessMod Rewrite

Regex Problem Overview


I've had to update my .htaccess from this:

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

to this:

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

to get it working behind an AWS Elasic Load Balancer.

It all seems to work fine on AWS, but in my local environment I'm stuck in a redirect loop.

How I can get this setup to work correctly in both environments?

Regex Solutions


Solution 1 - Regex

To make it work in both environments you can combine both conditions:

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

Solution 2 - Regex

I had a special case for a shared hosting (masterhost), everything was failing except:

  RewriteCond %{HTTP:X-Forwarded-Port} !443
  RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongregView Question on Stackoverflow
Solution 1 - RegexanubhavaView Answer on Stackoverflow
Solution 2 - RegexNick KovalskyView Answer on Stackoverflow