Back to Fred Mac Donald's Blog
I recently upgraded a website that used “standard” dynamic url’s to make use of SEO friendly url’s with some fancy mod_rewrite entries in the htaccess file.
Soon after I realized that the search engines still has the old dynamic url’s indexed and visitors routinely ended up on the dynamic url instead of the static url.
To solve the issue I basically have two options.
Obviously the first option is not really feasible so I had to come up with a quick and dirty hack to correct the issue. There are probably better options but this short script did the trick.
Since the static url can easily be constructed from the database on the page that display the content it was simple a matter of comparing the “request url” with the “expected url” and see if they are the same. If not redirect the visitor to the correct url with a php 301 header redirect.
Important point to remember is to tell the search engine what page is the preferred page to index using the rel:”canonical” tag
// Redirect to canonical url $req_url = $_SERVER['REQUEST_URI']; $art_name = strtolower($row_article['article_subject']); // get article name and make all lower case $art_name = preg_replace('/[^a-z0-9./]+/', '-', $art_name); // replace blanks and other characters $art_name = rtrim($art_name,"!?-_\. \t\n"); //chop off unwanted characters at end $art_name = '/article-'.$colname_article.'-'.$art_name.'.html'; // build seo url. $colname_article in this case is the record id of the article $canon = $host.'/article-'.$colname_article.'-'.$art_name.'.html'; // build canonical url $str_comp = strcmp($req_url,$art_name); // compare the two url'sif ($str_comp == '1') // if compare == '1' then redirect to seo urlnot correct because might return a value larger than 1 if ($str_comp != '0') // if compare == '0' then redirect to seo url { header("Location: $art_name",TRUE,301); exit; } // End Redirect to canonical url
Since I now had the proper canonical url I could add it as the proper canonical url in the page header or <head> section of my page as well.
< link rel = "canonical" href = "<?php echo $canon;?>" / >