I am trying to do a canonical redirect from this url
www.mysite.com/page.php?id=1&title=aaa
To this: www.mysite.com/1_aaa
I wrote this function:
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");
}
}
}
And in the page.php I put this code:
canonicalRedirect($url);
Retrieving the $url variable from a MySQL query. However when I try to run it I get this error (I am using Firefox): The page isn't redirecting properly
I am thinking that the page is self-redirecting but how can I solve this problem? Thanks
finally I managed to solve my problem. I rewrited my function like this:
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");
}
}
Then in the page.php code I wrote this:
// 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);
Bye!
The variable $canonicalURL
is not defined in your function, resulting in empty location for the redirect