静态站点中的大容量内部链接重定向方法


Bulk internal links redirect method in static site

我有一个由大约1500多个页面组成的静态网站。每一个HTML页面都有一个内部链接(我的意思是在页面本身编码),我想用一个新的链接替换它。

但是,不可能编辑所有这些页面,因为有成千上万的页面。

这里有一个例子:

  • 假设我有一个页面www.example.com/page.html
  • 该页面上有一个指向www.abc.com的超链接
  • 我希望此链接用www.xyz.com而不是www.abc.com替换/重定向

我已经有了一个MySQL表,其中有两列中的所有当前链接和新链接。

有没有一种方法可以通过使用.htaccess文件、PHP和MySQL重定向所有这些链接?如果可能的话,那么代码会是什么样子?

我找到了一种使用此脚本更改所有链接的方法。

<?php
require_once("connection.inc.php");
function get_value($file){
    //$html = file_get_contents($file,true);
    $dom = new DOMDocument('1.0');
    $dom->loadHTMLFile($file);
    $xpath = new DOMXPath($dom);
    $nodes = $xpath->query('//a/@href');
    foreach($nodes as $href) {
        return $href->nodeValue;            // echo current attribute value
        //$href->nodeValue = 'new value';   // set new attribute value
        //$href->parentNode->removeAttribute('href');  // remove attribute
    }
}
function put_value($file,$pattern){
    //$html = file_get_contents($file,true);
    $dom = new DOMDocument('1.0');
    $dom->loadHTMLFile($file);
    $xpath = new DOMXPath($dom);
    $nodes = $xpath->query('//a');
    $nodes->item(0)->setAttribute("href",$pattern);
    $dom->save($file);
}
$dir   = new RecursiveDirectoryIterator(__DIR__);
$flat  = new RecursiveIteratorIterator($dir);
$files = new RegexIterator($flat, '/'.html$/i');
foreach($files as $file) {
    $value=get_value($file);
    $query=mysql_query("SELECT new_links FROM site WHERE current_links='$value'");
    if(mysql_num_rows($query)==1){
        $value_orginal = mysql_result($query,0);
        put_value($file,$value_orginal);
        echo "The ".$file." has changed to ".$value."</br>";
    }
    else{
        die("die baby die :)");
    }
}
?>

您可以使用htaccess重定向重定向至使用.htaccess 的其他URL