为什么RewriteCond%{HTTPS}没有返回正确的值?

时间:2014-03-05 23:42:28

标签: .htaccess mod-rewrite drupal https no-www

我正在Drupal网站上工作,客户已要求我们删除“www”。来自网址。这非常简单,我以前做过;我只是在Drupal生成的.htaccess文件中注释出建议的行,如下所示:

# To redirect all users to access the site WITHOUT the 'www.' prefix,
# (http://www.example.com/... will be redirected to http://example.com/...)
# uncomment the following:
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

熟悉Drupal的.htaccess的人会知道环境变量protossl被设置在文件的顶部,如下所示:

# Set "protossl" to "s" if we were accessed via https://.  This is used later
# if you enable "www." stripping or enforcement, in order to ensure that
# you don't bounce between http and https.
RewriteRule ^ - [E=protossl]
RewriteCond %{HTTPS} on
RewriteRule ^ - [E=protossl:s]

这完全适用于我的本地环境,但是当我将更改部署到生产站点时,它就会中断。 www.mysite.com按预期重定向到mysite.com,但https://www.mysite.com 重定向到mysite.com而不是https://mysite.com。似乎%{HTTPS}变量即使在'on'时也会返回'off'。

我可以直接转到https://mysite.com,但效果很好。该站点的Apache访问日志显示“https://”,我希望它与我的所有HTTP请求一样。该站点使用负载平衡器(平衡器中只有一个节点)在RackSpace服务器上运行。 SSL证书位于RackSpace负载均衡器上。我尝试了以下步骤,没有任何结果:

  • 将RewriteCond替换为RewriteCond %{ENV:HTTPS} on [NC]
  • 将RewriteCond替换为RewriteCond %{SERVER_PORT} ^443$
  • 上述RewriteCond的多种变体和组合
  • $conf['https'] = TRUE;添加到settings.php

这正在驱使我的同事,我疯了。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:5)

anubhava节省了一天!解决方案是按照他的建议使用%{HTTP:X-Forwarded-Proto}变量。我更新了.htaccess的协议检测位,如下所示:

# Set "protossl" to "s" if we were accessed via https://.  This is used later
# if you enable "www." stripping or enforcement, in order to ensure that
# you don't bounce between http and https.
RewriteRule ^ - [E=protossl]
# The default proto detection provided by Drupal does not work on our
# production server because it sits behind a load-balancing server.
# This additional RewriteCond makes sure we can detect the forwarded proto
RewriteCond %{HTTP:X-Forwarded-Proto} https [OR]
RewriteCond %{HTTPS} on
RewriteRule ^ - [E=protossl:s]

我会称这是一个至关重要的因素,因为好好去