Migrating Old Permalinks to WordPress

Now that I migrated to WordPress for blogging, the permalinks of my previous blog entries have changed.

For example:

/article_php_5_enterprise_edition_available_online

changed to:

/2006/11/26/article-php-5-enterprise-edition-available-online/

My initial idea was to use mod_rewrite by adding a RewriteRule for each old link redirecting to the new location, but that looked like a lot of copy&paste to me and would not teach me anything new.

Instead, I chose to redirect requests for old links to the WordPress search page. Try it out yourself: Click on this old permalink /article_php_5_enterprise_edition_available_online and you will be redirected to the search page, which displays the blog entry to you as a search result. This looks like a more flexible solution to me, just in case that my permalinks might change again one day.

The implementation was simple. I added a few lines of PHP code to the 404.php page of my WordPress theme as described in the support topic 404 Search Function for WordPress. I also added a header redirect directive.

This is the full code:

[php]

// Adjust if WordPress is located in subdirectory,
// e.g. http://www.example.com/weblog. Otherwise leave empty.
$blog_uri = ‘weblog’;

// Don’t change from here.
$search_url = $blog_uri.’/?s=’;
$search_term = urldecode( substr($_SERVER[‘REQUEST_URI’],1) );
$find = array(“‘”.$blog_uri.”‘”, “‘/'”, “‘[-/_]'”) ;
$replace = ” ” ;
$new_search = preg_replace($find, $replace, $search_term);
$new_search = urlencode($new_search);

// Redirect to search page.
header(“Location: /”.$search_url.$new_search.”&http_status=404″);
exit;
[/php]

Notice that for security reasons, I use urlencode() for the search page URL to avoid HTTP Response Splitting.

One thought on “Migrating Old Permalinks to WordPress

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s