views:

835

answers:

2

I currently have a blog set up with WordPress using URLs like so:

www.domain.com/blog/?pid=384092817

This was before I knew anything about anything. There's a significant amount of content there now and I want to change my URL structure to:

www.domain.com/my-post-title-384092817

Is there a way to set up my .htaccess and mod rewrite so when users go to the first url they get a 301 redirect to the second URL? I know to change my WordPress address (URL) setting from www.domain.com/blog to www.domain.com and my permalink setting to /%postname%-%post_id%, but how do I tell the old URLs to redirect to the new ones?

+3  A: 

Do you actually mean that when users go to the second URL, it will be rewritten to the first? That can be done with

RewriteRule /blog/.+-(\d+)$ /blog/?pid=$1

If you want to send 301 redirects from the old URLs to the new ones, then you can't really do that with an .htaccess file. The reason is that Apache's mod_rewrite doesn't have access to the title of your post, so it won't know what title to insert in the URL. You'd have to do that redirect with PHP.

EDIT: y'know what, actually that's not entirely true. You can do some pretty crazy things with the RewriteMap directive, such as instructing Apache to ask an arbitrary program to perform the rewriting, and in that way you could have, say, a PHP script that does some database work to figure out what the title is and rewrites the URL appropriately based on that. But that seems like a way overcomplicated solution and I wouldn't suggest doing it - it'll be much cleaner and easier to just send the redirect directly from PHP.

David Zaslavsky
I need this url: /blog/?pid=234 to 301 redirect to this url: /my-post-title-234
go minimal
Guess I misunderstood your question at first, but look at my edited answer: basically you can't (or at least shouldn't) do that with mod_rewrite.
David Zaslavsky
what about a simplified version?Going from /blog/?pid=123 to /index.php?p=123 and then letting WordPress handling the rest...
go minimal
+2  A: 

Depending on your WP version, you can just use the Permalink redirect plugin -- should do the trick for you within WordPress and without mod_rewrite. However, as of WordPress 2.3, a lot of this should work automatically. At that point, the only thing you should have to do is redirect all your /blog/... requests to the route, which you can do via mod_rewrite roughly like this:

RewriteRule ^blog(.*) $1 [QSA]
Fortes