概述
我正在尝试重写:
http://www.foo.com/bar
到安全版本https://www.foo.com/bar
,则https://www.foo.com/bar
至https://www.foo.com/index.php?location=bar
我的index.php
页面只是输出$_GET
变量。
代码
.htaccess
:
RewriteEngine On
RewriteBase /
RewriteRule ^https://%{SERVER_NAME}%{REQUEST_URI} [L,QSA,R=permanent]
RewriteRule ^([^/]*)$ /?location=$1 [L]
index.php
:
<?php print_r($_GET); exit; ?>
问题
- 如果我访问
www.foo.com/bar
,我会看到500服务器错误 - 如果我注释掉处理
$_GET
"位置"变量的规则并访问foo.com
,它不会重定向到网站的安全版本
更新
.htaccess
:
RewriteEngine on
# if https is off (it is on)
#RewriteCond %{HTTPS} off
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)/?$ ?location=$1 [L,QSA]
访问以下会导致重定向循环错误:
- www.foo.com/bar
- www.foo.com/index.php?location=bar
- www.foo.com/?location=bar
- www.foo.com?location=bar
然而,如果我评论这一行:
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]
页面按预期加载:
阵列([位置]=>条)
这让我相信问题出在HTTPS重定向上,我该如何解决?
这个规则就是问题所在:
RewriteRule ^https://%{SERVER_NAME}%{REQUEST_URI} [L,QSA,R=permanent]
由于语法是
RewriteRule matching-pattern target [flags]
此外,您还需要在两个规则中使用RewriteCond
来避免规则循环。
你可以通过用替换你的代码来修复它
DirectoryIndex index.php
RewriteEngine on
# if https is off
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)/?$ ?location=$1 [L,QSA]