Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

apache - .htaccess redirect loop when trying to add forced HTTPS rule (Amazon Elastic Beanstalk)

I started receiving this error after trying to incorporate a rule to force HTTPS in the production environment. The BWC_ENV environment variable can have a handful of different values: "prod", "stage", "ben_local", "nam_local", etc.

Here's my .htaccess:

RewriteEngine On

# Force HTTPS
RewriteCond %{HTTPS} !=on
RewriteCond %{ENV:BWC_ENV} ^prod$
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Parse the subdomain as a variable we can access in our scripts
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST}        !^www
RewriteCond %{HTTP_HOST}         ^([^.]+).([^.]+).([^.]+)$
RewriteRule ^(.*)$ /$1?subdomain=%1

# Ditto for the path; map all requests to /index.php
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !robots.txt
RewriteRule ^(.*)$ /index.php?path=$1 [L,QSA] 

# robots.txt - supply the correct one for each environment
RewriteRule ^robots.txt$ /robots.prod.txt [NC] 
RewriteCond %{ENV:BWC_ENV} !prod
RewriteRule ^robots.prod.txt$ /robots.stage.txt [NC] 

Edit

What's more, if my .htaccess only contains the following, this will cause a redirect loop too. Why could this be?

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It turns out this is an Amazon Elastic Load Balancer thing. You have to use Amazon's X-Forwarded-Proto header to accomplish this:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule !/status https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...