PHP规范重定向

PHP规范重定向,php,http-status-code-301,http-redirect,Php,Http Status Code 301,Http Redirect,我正在尝试从此url执行规范重定向 www.mysite.com/page.php?id=1&title=aaa 致此:www.mysite.com/1_aaa 我写了这个函数: function canonicalRedirect($url) { if (strtoupper($_SERVER['REQUEST_METHOD']) == 'GET') { $canonical = $url; if (!preg_match('/'.str_re

我正在尝试从此url执行规范重定向

www.mysite.com/page.php?id=1&title=aaa

致此:www.mysite.com/1_aaa

我写了这个函数:

function canonicalRedirect($url)
{

    if (strtoupper($_SERVER['REQUEST_METHOD']) == 'GET')
    {
        $canonical = $url;
        if (!preg_match('/'.str_replace('/','\/',$canonical).'/', $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']))
        {
            header('HTTP/1.0 301 Moved');
            header('Cache-Control: no-cache');
            header("Location: $canonical");
        }
    }
}
在page.php中,我输入了以下代码:

canonicalRedirect($url);
从MySQL查询中检索$url变量。然而,当我尝试运行它时,我得到了这个错误(我使用的是Firefox):页面没有正确重定向


我认为页面是自动重定向的,但是我如何解决这个问题呢?谢谢

您的函数中没有定义变量
$canonicalURL
,导致重定向的位置为空

最后我设法解决了我的问题。我像这样重写了我的函数:

function canonicalRedirect($url)
{
            //Check that there is not query string in the url
    if(preg_match('/\?/', $_SERVER["REQUEST_URI"])) {
        header('HTTP/1.0 301 Moved');
        header('Cache-Control: no-cache');
        header("Location: $url");
    }   
}
然后在page.php代码中,我写了以下内容:

 // code to retrieve the canonical url from MySQL
 // $row is the array with the url data and $canonicalurl is obviously the canonical url


if($_GET['title'] != $row['url_title']) {

  header("HTTP/1.1 301 Moved");
  header('Status: 301 Moved Permanently', true);
  header("Location: ".$canonicalurl."",TRUE,301);
}
else {
}

canonicalRedirect($canonicalurl);

再见

php有可能生成这样的URL吗?对不起,我错发了这篇文章,现在我要编辑它(我首先给我的变量起了另一个名字)。。。然而问题仍然存在,我也想要答案@FG@AspiringAqib重定向是通过HTTP头完成的。使用PHP,您可以操作发送到client@AspiringAqib:mod_rewrite无法读取数据库,人们仍然可以根据数据库中的某些值使用PHP/ASP.NET(etc)进行301重定向。OP也在做同样的事情,但他/她在preg_赛道上遇到了问题。你到底从数据库中检索到了哪一部分?我的意思是你的
$url
变量包含什么-
id=1&title=aaa
1_-aaa
?我的$url变量包含1_-aaaTry删除HTTP/1.0头,而是添加301作为位置头的第二个参数。还有,url是什么样子的?您的问题不包含有关传递给函数的值的信息。嗨,Darhazer,我尝试按照您的建议执行,但没有成功。我正在向函数传递我希望页面重定向到的url。我希望该页面被重定向到。我将传递函数canonicalRedirect的值。