views:

141

answers:

2

I'm migrating a custom coded blog over to Wordpress, and have to set up a redirect that will handle all of the blog posts.

I need to redirect from this:

/oldblogdirectory/Old_Blog_Posts_Looked_Like_This.htm

to:

/newblogdirectory/new-blog-posts-look-like-this/

Any ideas on the regex for a redirect like this?

+2  A: 

Try this mod_rewrite rules:

RewriteEngine on
RewriteRule ^(oldblogdirectory/[^_]*)_([^_]*)_(.*) /$1-$2-$3 [N]
RewriteRule ^(oldblogdirectory/[^_]*)_(.*) /$1-$2
RewriteRule ^oldblogdirectory/(.+)\.htm$ /newdirectory/$1/ [L,R=301]

But for the uppercase to lowercase conversion you’ll either need a mapping like the internal tolower function or you use PHP for both.

Gumbo
This doesn't seem to work. Any suggestions?
SerpicoLugNut
@SerpicoLugNut: Can you elaborate on that?
Gumbo
When I use it, it doesn't produce the desired effect of redirecting the old posts location to the new. I am placing this in my root .htaccess. For reference, the site structure is this:old:mydomainname.com/oldblogdir/archives/old_blog_posts_look_like_this.htmnew:mydomainname.com/newblogdir/archives/new-blog-posts-look-like-this/and I am modifying the .htaccess file located here:mydomainname.com/.htaccess
SerpicoLugNut
It's actually clever to replace two underscores in the first rule and an eventually single one in the second, but then the single underscore in the second rule would have to be optional. Otherwise the rules won't match if there's an **even number** of underscores (or no underscore).
Pascal
@SanHolo: You’re right. Fixed it.
Gumbo
This works, except if there's no underscore in the old url. ;)
Pascal
+2  A: 

Gumbo's approach is certainly the way to do it. I made two test directories:

oldblogdir/archives/blog_posts_look_like_this.htm
newblogdir/archives/blog-posts-look-like-this

And the following RewriteRules redirect successfully. They are only slightly changed to Gumbo's proposal:

RewriteEngine on
RewriteBase /

RewriteRule ^(oldblogdir/archives/[^_]*)_(.*) $1-$2 [N]
RewriteRule ^oldblogdir/archives/(.*?)\.htm$ newblogdir/archives/$1 [R,NC,L]

Note that the [N] causes the .htaccess file to be re-evaluated until the RegEx no longer matches. Therefore you should put it at the very top of the file.

Pascal
That will cause an infinite recursion.
Gumbo
I don't see why. Can you give an example URL that would cause an infinite recursion?
Pascal