2012-12-15 43 views
-1

我想從這個網址PHP規範重定向

www.mysite.com/page.php?id=1 &標題做一個規範的重定向= 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):本網頁沒有正確重定向

我想到的是,網頁自重定向,但我怎麼能解決這個問題?由於

+0

你正準確地從數據庫中檢索哪個部分?我的意思是你的'$ url'變量包含什麼?'id = 1&title = aaa'或'1_aaa'? – brezanac

+0

我的$ url變量包含1_aaa –

+0

嘗試刪除HTTP/1.0標題,並將301添加爲位置標題的第二個參數。此外,該網址的外觀如何? –

回答

-1

我終於成功地解決我的問題。在page.php文件代碼

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

然後我寫了這個:我rewrited我函數這樣

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

再見!

0

變量$canonicalURL是不是在你的函數定義,導致空位置重定向

+0

是否有可能使用PHP來製作此類網址? –

+0

對不起,我拼錯了帖子,現在我要編輯它(我首先給了我的變量另一個名字)...然而問題仍然存在 –

+0

woah男人我也想要答案! @FG –