【问题标题】:PHP canonical redirect [closed]PHP规范重定向[关闭]
【发布时间】:2012-12-03 07:33:59
【问题描述】:

我正在尝试从此网址进行规范重定向

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):页面未正确重定向

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

【问题讨论】:

  • 您究竟从数据库中检索哪一部分?我的意思是您的 $url 变量包含什么 - id=1&title=aaa1_aaa
  • 我的 $url 变量包含 1_aaa
  • 尝试删除 HTTP/1.0 标头,而是添加 301 作为位置标头的第二个参数。另外,网址是什么样的?
  • 您的问题不包含有关您传递给函数的值的信息。
  • 您好 Darhazer,我尝试按照您的建议进行操作,但没有成功。我将希望页面重定向到的 url 传递给函数。 EG 我希望将页面mysite.com/page.php?id=1&title=aaa 重定向到mysite.com/1_aaa。我将 mysite.com/1_aaa 作为函数 canonicalRedirect 的值传递。

标签: php http-status-code-301 http-redirect


【解决方案1】:

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

【讨论】:

  • 用php可以制作这样的url吗?
  • 对不起,我拼错了帖子,现在我要编辑它(我首先给我的变量取了另一个名字)......但是问题仍然存在
  • 哇,我也想要答案! @FG
  • @AspiringAqib 重定向是通过 HTTP 标头完成的。使用 PHP,您可以操作发送到客户端的 HTTP 标头
  • @AspiringAqib:mod_rewrite 无法读取数据库,人们仍然可以根据数据库中的某些值使用 PHP/ASP.NET(等)进行 301 重定向。 OP 也在做同样的事情,但他/她在 preg_match 线上遇到了问题。
【解决方案2】:

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

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);

再见!

【讨论】: