2013-02-25 169 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