我有这个我不知道如何解决的大问题。我有一个重定向到网址的脚本。
到目前为止,我有:
//do some mysql
$geo_included = true; //trying to fix infinite redirect loop.
if($geo_included === true){
header('Location: '.$url["url"]); //this is causing the issue with redirect loop
}
例如$url["url"]是:www.google.com
但是当我转到该PHP文件时,它将重定向到:
www.sitename.com/www.google.com
并假设存在无限重定向循环。注意:上面的标头位置脚本不在 while/for/foreach 循环中。
这是我对/目录的 .htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?group=$1 [L]
有什么想法吗?
您需要在 scheme 中包含完全限定的域名,否则它会被解释为在当前域中:
header('Location: google.com'); // Redirects to http://cursite.com/www.google.com
header('Location: http://google.com'); // Redirects as expected
如果您不确定您的 URL 是否包含方案,请检查 parse_url
中的结果。
$url_scheme = parse_url($url, PHP_URL_SCHEME);
// www.google.com -> NULL
// http://google.com -> string(4) "http"
// ftp://site.com -> string(3) "ftp"
这里的快速概念验证解决方案是在 URL 前面附加http://
,如下所示:
$geo_included = true;
if ($geo_included) {
header('Location: http://' . $url["url"]);
}
我说"概念验证"是因为你应该做的是确保$url["url"]
始终附加一个协议。要么在它进入数据库之前,要么在这个代码片段中,通过检查$url["url"]
值以查看它是否http://
或https://
,如果没有,则在前面加上它。这里有一个快速组合的例子,说明我的意思应该有效:
$geo_included = true;
if ($geo_included) {
$protocol = (!preg_match("~^(?:ht)tps?://~i", $url["url"])) ? 'http://' : null;
header('Location: ' $protocol . $url["url"]);
}
带有$protocol = …
的行执行我之前解释的检查。默认值是添加http://
(如果不存在(。
另外,请注意我删除了=== true
,因为if ($geo_included) {
基本上是一回事。