Mehadi Hasan
Mehadi Hasan

Reputation: 21

Bulk internal links redirect method in static site

I have a static site consisting of about 1500+ pages. Each one of those HTML pages has an internal link (I mean coded on the page itself) that I want to replace with a new one.

But, it is not possible to edit all those pages as there are thousands of them.

Here is an example:

I already have a MySQL table in which I have all the current links vs the new links in two columns.

Is there a way to redirect all these links by using the .htaccess file, PHP and MySQL? If it is possible then what would be the code look like?

Upvotes: 0

Views: 63

Answers (2)

Mehadi Hasan
Mehadi Hasan

Reputation: 21

I found a way to change all the links using this script.

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

Upvotes: 1

Navneet Garg
Navneet Garg

Reputation: 1374

you can use htaccess redirection Redirect to a Different URL using .htaccess

Upvotes: 0

Related Questions