[英]Htaccess conditional https for static pages
我的网站已启用HTTPS,并且所有页面仅使用HTTPS进行服务。 现在,客户有一个要求,他希望在其中将静态页面(例如about-us
, termsofus
为HTTP页面而不是HTTPS 。 这意味着即使用户尝试以HTTPS形式打开about-us
页面,它也应重定向到about-us
HTTP版本。
我的.htaccess
代码如下:
Options -Indexes
<IfModule mod_rewrite.c>
RewriteEngine on
#RewriteCond %{HTTPS} off
#RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^\/about-us
RewriteCond %{REQUEST_URI} !^\/termsofus
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} \/about-us [OR]
RewriteCond %{REQUEST_URI} \/termsofus
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
</IfModule>
问题:每当我打开about-us
页面的HTTP / HTTPS版本时,它都会继续将我重定向到index.php
。 例如: https://example.com/about-us
: https://example.com/about-us
到https://example.com/index.php
该站点使用PHP YII框架。
使用THE_REQUEST
变量而不是REQUEST_URI
。 THE_REQUEST
变量表示Apache从您的浏览器接收到的原始请求, 在执行某些重写规则后不会被覆盖 。
Options -Indexes
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{THE_REQUEST} !\s/+(about-us|termsofus) [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
RewriteCond %{HTTPS} on
RewriteCond %{THE_REQUEST} \s/+(about-us|termsofus) [NC]
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
在测试此更改之前,请确保清除浏览器缓存。
anubhava的答案已经解决了这个问题,并提供了一个很好的解决方案。 我想我只是参考您的原始代码,对您所说的示例发生了什么提供一些补充说明:
例如:
https://example.com/about-us
:https://example.com/about-us
到https://example.com/index.php
要求提供https://example.com/about-us
:
这符合您的第二条规则(HTTPS为“ on”,并请求about-us
),并重定向到http://example.com/about-us
(即,返回HTTP)。
重定向的请求(即http://example.com/about-us
)现在与最后一条规则匹配,并在内部被重写为index.php
(前端控制器)。
但是,在每个目录的.htaccess
文件( 目录上下文)中,“重写的请求将交还给URL解析引擎”,并且该过程有效地重新开始。 REQUEST_URI
服务器变量也被更新以保存重写的URL,即。 /index.php
。
在第二次通过.htaccess
文件时,请求(现已重写为http://example.com/index.php
)与您的第一个规则匹配(HTTPS为“ off”且请求不是/about-us
或/termsofus
)因此,该请求(第二次)被重定向到https://example.com/index.php
。 (内部重写实际上已更改为外部重定向 。)
重定向的请求(现在为https://example.com/index.php
)与您的.htaccess
文件中的任何规则均不匹配,因此将保持不变。 页面已投放。
如果检查网络流量,则应该看到上面提到的两个外部重定向。
另一种可能的解决方案是在最后一个RewriteRule
上使用END
标志(仅适用于Apache 2.4+)。 这有效地结束了URL重写过程,因此该过程在步骤#2处停止。 尽管我仍然会喜欢anubhava的解决方案,并对照THE_REQUEST
检查,但该解决方案在Apache 2.2上有效,并且在您引入其他重写后仍然可以使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.