
Originally Posted by
Trikkur
Please explain!
I always do my 301s in htaccess. Should I be using something different, or is there a way to add multiple stuff easily.
Well, as an example, I migrated a site today to a new system. There is a WordPress install on the system. And the old news backend was a custom system. So I made a table (explained below) and used this code in the WordPress index.php:
PHP Code:
<?php
/**
* Front to the WordPress application. This file doesn't do anything, but loads
* wp-blog-header.php which does and tells WordPress to load the theme.
*
* @package WordPress
*/
//Code to redirect old news to new news pages
include("../database-config.php"); //I changed this for PAL :)
$requesturi = $_SERVER['REQUEST_URI'];
if(preg_match("/\/news\/(.+).shtml/",$requesturi,$matches)) {
$slug = $matches[1];
$slug = addslashes($slug);
$query = "SELECT `newsid`
FROM `news301redirects`
WHERE `slug` LIKE CONVERT( _utf8 '$slug'
USING latin1 )
COLLATE latin1_swedish_ci
LIMIT 0 , 1 ";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
if($rows == 0) { //no slug found
header('HTTP/1.1 301 Moved Permanently', true, 301);
header("Location: /news/");
exit();
}
$row = mysql_fetch_row($result);
$articleid = $row[0];
$query = "SELECT `post_name`
FROM `wp_posts`
WHERE `ID` = $articleid
LIMIT 0 , 1 ";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
if($rows == 0) { //no id found
header('HTTP/1.1 301 Moved Permanently', true, 301);
header("Location: /news/");
exit();
}
$row = mysql_fetch_row($result);
$newarticleslug = $row[0];
$newurl = "/news/$newarticleslug-$articleid/";
header('HTTP/1.1 301 Moved Permanently', true, 301);
header("Location: $newurl");
exit();
}
/**
* Tells WordPress to load the WordPress theme and output it.
*
* @var bool
*/
define('WP_USE_THEMES', true);
/** Loads the WordPress Environment and Template */
require('./wp-blog-header.php');
?>
My old news structure was /news/[slug].shtml. So I took the old news table, deleted every column except id and slug/url (which used to be written by hand). Then I imported the 700some old posts into WordPress using the same ids. Then I use the two queries above (with some error/bug fixes to make sure everything works okay) to determine the redirected URL. Then I use two php header lines to send the user and search engine to the right place.
No htaccess needed.
Let me know if you have questions, but this was a 20 minute project max, which is much better than putting 750 lines in my htaccess imo.
Bookmarks