Htaccess: Need to redirect query string

I’m trying to make…


with the rewrite rule below but it fails on me.

RewriteRule ^blog/([^/]+)/?$ /blog.php?post_id=$1 [L]

I would try something like this:

RewriteRule ^blog/([a-z-]+)/?$ /blog.php?post_id=$1 [L]

Of course, if you’re using the title in the URL, you’re going to get the title as ‘post_id’. You will need to match the title to a post in your PHP code.

So you’re saying i’ll have to post the title to the post_id?

Please walk me through this a bit.

Here is one way adding the ‘slug’ to the db

id 22
slug "title-of-the-blog-post"
title "Title of the Blog Post"
text_blog "blah ...

// **security check of GET var omitted for brevity**
$sql = "select id from blog_table where slug = '. $_GET['post_id'] .'"

Another way is to maintain a mapper between titles and ids as say a PHP array in a static file.

$blog_posts[22] = "title-of-the-blog-post";

$key = array_search($_GET['post_id'], $blog_posts)


added array_search advice

[fphp]array_search[/fphp] — Searches the array for a given value and returns the corresponding key if successful

I believe there is a way of getting Apache to do the lookup vs a static file too, but I did not use it.

ps here is a similar discussion from earlier this week

What does everyone else do?


Moved from PHP forum? huh?

There was a thread some time back where this was directly addressed (as well as within my signature’s tutorial - with code). Essentially, you cannot get from title-of-the-blog-post to a post_id value (without RewriteMap which required Apache config file access) so ditch post_id and use title=$1 (after converting the spaces to _'s then back to query the database). For an example, Welcome - Wilderness Wally’s Americana! uses EXACTLY this technique but without the blog subdirectory. The only tricky part(s) are ensuring UNIQUE titles and ensuring that only acceptable characters are allowed in the title.



My next question was going to be… how can you ensure unique titles without an ID? How do blog engines like wordpress handle it?


I use MySQL and it has the ability to make any field unique, including, of course, the title field. Set like that, even Wilderness-Wally can’t duplicate titles.