2013-02-25 149 views
2

有超過3000的URL我必須301 redirect。我無意中在很多URL中重複使用了城市/州,這使得它們重複且時間過長。我可以以編程方式生成超過3000個if statements的URL,它需要爲301 redirected。但是,這將會是每一頁頂部的數千行代碼。以下是使用此方法的3000多個網址中的3個示例redirectsPHP 301重定向 - 3000動態URL的

if($_SERVER['REQUEST_URI'] == 'central-alabama-community-college-alexander-city-alabama') { 
    header("HTTP/1.1 301 Moved Permanently"); 
    header("Location: http://www.website.com/colleges/central-alabama-community-college-alexander-city"); 
    exit; 
    } 

if($_SERVER['REQUEST_URI'] == 'athens-state-university-athens-alabama') { 
    header("HTTP/1.1 301 Moved Permanently"); 
    header("Location: http://www.website.com/colleges/athens-state-university-alabama"); 
    exit; 
    } 

if($_SERVER['REQUEST_URI'] == 'auburn-university-auburn-alabama') { 
    header("HTTP/1.1 301 Moved Permanently"); 
    header("Location: http://www.website.com/colleges/auburn-university-alabama"); 
    exit; 
    } 

這種方法是有效的,但我擔心這是不好的做法。另一種方法是使用關聯數組。這是這樣的:

$redirects = array('central-alabama-community-college-alexander-city-alabama' => 'central-alabama-community-college-alexander-city','athens-state-university-athens-alabama' => 'athens-state-university-alabama','auburn-university-auburn-alabama' => 'auburn-university-alabama'); 

if(array_key_exists($_SERVER["REQUEST_URI"], $redirects)) { 
    header("HTTP/1.1 301 Moved Permanently"); 
    header("Location: http://www.website.com/colleges/$redirects[1]"); 
    exit; 
    } 

我可以有一點點錯誤,但你可以看到它應該做什麼。什麼是最好的方法來解決這個問題?我不認爲我可以有效地使用.htaccess,因爲每個重定向有多獨特。每個網址都沒有一致的變量。有什麼想法嗎?

回答

2

我會使用關聯數組,但你可以使用換行來保持它的清晰,就像這樣:

$redirects = array(
    'central-alabama-community-college-alexander-city-alabama' => 'central-alabama-community-college-alexander-city', 
    'athens-state-university-athens-alabama' => 'athens-state-university-alabama', 
    'auburn-university-auburn-alabama' => 'auburn-university-alabama', 
    'etc...', 'etc...' 
); 

另一種選擇是這些信息存儲在數據庫中,並期待它了這種方式,這種方式您不需要維護可能因安全原因被鎖定的PHP文件本身。

+0

感謝DAJ。你知道,如果這從SEO的角度來看可接受的做法?我擔心這樣做超過3000個URL是由谷歌/ SERPS皺起了眉頭。 – Graham 2013-02-25 07:21:49

+0

這是完全可以接受的,只要這些重定向是永久的(如301所示),並且您將用戶重定向到規範地址。 – Dai 2013-02-25 07:22:59

+0

要說清楚,你的意思是在每頁的中都有這樣的東西嗎? *** <鏈路的rel = 「規範」 HREF = 「http://www.website.com/colleges/central-alabama-community-college-alexander-city」/> – Graham 2013-02-25 07:25:33

0

我覺得把這個在您的.htaccess文件將是最好的解決方案。它可以很容易地實現。我也覺得這比將所有邏輯放入PHP文件更好。

RewriteEngine On 
Redirect 301 /old-page.html http://www.mysite.com/new-page.html 
+2

這不是一個真正的選擇,因爲有超過3000個URI來重定向。 – Dai 2013-02-25 07:20:14

+0

@Dai它是每個重定向的一行,就像您的解決方案一樣。我寧願讓我的301的.htaccess比PHP。 – mcryan 2013-02-25 07:26:42

+0

我擔心Mod_Rewrite不會將關鍵字存儲在關聯數組中,而是存儲緩慢的正則表達式。而使用PHP關聯數組,你知道它總是很快。 – Dai 2013-02-25 07:46:54

1

我覺得你應該把你的重定向在DB,

然後使用的.htaccess重定向到一個單一的PHP腳本,做301重定向到正確的URL。

+0

你可以舉一個.htaccess代碼的例子嗎?我也有點困惑在存儲在數據庫中。每行數據都有舊/新的URL存儲。這是我想要的嗎?你能提供一個更詳細的答案,說明如何做這個解決方案嗎?謝謝。 – Graham 2013-02-25 07:47:21