.htaccess to query the database, then rewrite the URL

to put it as simply as I can, I’d like to rewrite the URI from this:

http://sitename.com/category.php?cat_id=1

to this:

http://sitename.com/category/music/

Is it possible for .htaccess to access the database and figure out what cat_name is associated with the cat_id from the URI?

No, it doesn’t need to, and you’re looking at this backwards.

mod_rewrite takes the request for /category/music/ and rewrites it to category.php?cat_id=1. This lets your category.php script actually handles serving a page for that “prettified” URL. Rewriting URLs involves transforming request URIs (typically URLs that don’t correspond to any real file), to the real file that will serve a webpage in response.

I suggest rewriting /category/music/ to category.php?cat_name=music (which you can do with a regular expression that matches any category name), then category.php looks up the appropriate ID for “music” in the database.

It may sound ridiculous, but having it backwards makes it very difficult to understand! Thanks for pointing that out (seriously). I’ve now got it serving up the page with this:

RewriteEngine on
RewriteRule ^/?([A-Za-z]+)$ category.php?cat_id=$1 [L][L]

Then I can have the category.php script find out the cat_id. How can I handle category names with spaces?

Most CMS’s replace them with hyphens when generating URLs. They also explicitly store the slug (“category-name”) corresponding to the ID in the database, rather than rely on convention, so that you have the option of changing them.

gg,

Dan is mostly correct. If you’ve read the mod_rewrite tutorial linked in my signature, you’ll know how to do this all - including using something other than the ID for the link as well as using the underscore ( _ ) to replace spaces in the URI (and back again to access the db). In fact, you can see this in operation at http://wilderness-wally.com where I use Wally’s titles to access the db for each of his many stories.

IF you REALLY wanted to use the title to access the db to rewrite the URI, you can use a RewriteMap but that requires access to httpd.conf as it can take down Apache. As Dan pointed out (and I’ve demonstrated with Wally’s site), you don’t need to do that!

Regards,

DK

thank you both. Excellent replies, and I’ll look into those resources before going further.