尝试添加强制HTTPS规则时的.htaccess重定向循环(Amazon Elastic Beanstalk)

时间:2013-09-05 23:02:22

标签: apache mod-rewrite amazon-ec2 elastic-beanstalk amazon-elb

尝试合并规则以在生产环境中强制HTTPS后,我开始收到此错误。 BWC_ENV环境变量可以有一些不同的值:“prod”,“stage”,“ben_local”,“nam_local”等。

这是我的.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] 

修改

更重要的是,如果我的.htaccess只包含以下内容,这也会导致重定向循环。为什么会这样?

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

2 个答案:

答案 0 :(得分:22)

事实证明这是Amazon Elastic Load Balancer的事情。您必须使用亚马逊的X-Forwarded-Proto标头来完成此任务:

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

答案 1 :(得分:1)

您在少数规则中缺少L个标记。键入将代码更改为:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# 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 %{QUERY_STRING} !^$
RewriteCond %{HTTP_HOST}        !^www
RewriteCond %{HTTP_HOST}        ^([^.]+)\.[^.]+\.[^.]+$
RewriteRule ^(.*)$ /$1?subdomain=%1 [L,QSA]

# 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 [L,NC] 
RewriteCond %{ENV:BWC_ENV} !prod
RewriteRule ^robots.prod.txt$ /robots.stage.txt [NC,L]