PHP 301重定向-超过3000个动态URL';s


PHP 301 redirect - over 3,000 dynamic URL's

301 redirect有3000多个URL。我不小心在很多URL中重复了城市/州的使用,这使得它们重复且太长。我可以用程序为需要301 redirected的URL生成3000多个if statements。但是,这将是每一页顶部的数千行代码。下面是使用这种方法的3000+URL中的3个示例redirects

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,因为每个重定向都是唯一的。每个URL都没有一致的变量。有什么想法吗?

我会使用关联数组,但你可以使用换行符来保持它的可读性,比如:

$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文件本身,因为安全原因可能会将其锁定。

我认为你应该把你的重定向放在数据库中,

然后使用.htaccess重定向到一个php脚本,该脚本将301重定向到正确的URL。

我认为把它放在.htaccess文件中是最好的解决方案。它可以很容易地实现。我还觉得这是一个比将所有逻辑放入PHP文件更好的解决方案。

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