我遇到了一种我无法解释或纠正的怪异行为。我需要将每个HTTP
请求重定向到HTTPS
。我使用以下代码:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# The query string in the rewrite is for testing purposes
RewriteRule (.*) /index.php?url=$1&%{REQUEST_URI}&http=%{HTTPS} [L]
到目前为止,它有效。然后,我需要一个页面为HTTP
,所以我添加了一些重写条件:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} ^/not-https
RewriteRule .* http://%{HTTP_HOST}%{REQUEST_URI} [R=302,L]
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/not-https
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /index.php?url=$1&%{REQUEST_URI}&https=%{HTTPS} [L]
现在,这里发生了什么。出于某些原因,访问/not-https
页面时,会重定向到/index.php?url=not-https&/not-https&https=off
以下是重定向/显示网址后面的GET请求地图。
GET: http://example.com/test
-> https://example.com/test with proper $_GET
GET: http://example.com/test.jpg
-> https://example.com/test.jpg with no $_GET (file exists)
GET: https://example.com/not-https
-> http://example.com/not-https
-> http://example.com/index.php?url=not-https&/not-https&https=off
我的问题是为什么not-https
会更改显示的网址(因此,弄乱我的应用程序)?
答案 0 :(得分:1)
正在发生这种情况,因为REQUEST_URI
变量的值在最后一条规则中变为/index.php?...
,使条件!^/non-https
在第二条规则中成功并使其执行该规则。
将前两条规则更改为:
RewriteCond %{HTTPS} on
RewriteCond %{THE_REQUEST} \s/+not-https [NC]
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
RewriteCond %{HTTPS} off
RewriteCond %{THE_REQUEST} !\s/+not-https [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
与REQUEST_URI
不同,变量THE_REQUEST
在执行其他内部重写后不会更改它的值。