views:

212

answers:

2

Hi everyone,

My question is a simple one, but I can't seem to find the answer. I'm currently working on some URL rewriting for a website, but I have encountered a problem. Currently the most basic rule I have goes something like this:

RewriteRule ^([a-zA-Z]+)/(([a-zA-Z]+)/?$ index.php?mod=$1&com$2

This works in most cases, and I have some special cases for where this doesn't apply, however one of the pages needs to pass a lot of information through the URL, and I want to automatically rewrite this. Some examples:

website.com/asdf/jkl/id/5/page/2 should become website.com/index.php?mod=asdf&com=jkl&id=5&page=2

website.com/qwer/yuio/search/keyword/sort/alpha should become website.com/index.php?mod=qwer&com=yuio&search=keyword&sort=alpha

Is this possible? I could really use some help here... Thanks! :)

A: 

You could use a recursive rule:

RewriteRule ^([a-zA-Z]+)/([a-zA-Z]+)/?$ index.php?mod=$1&com$2 [L,QSA]
RewriteRule ^([^/]+/[^/]+)/([^/]+)/([^/]+)/?(.*) $1/$4?$2=$3 [QSA]

But it sure would be easier to parse the request path with PHP.

Gumbo
Hmm, your example seems to be crashing my apache :P Good idea on the recursiveness though.
Aistina
Aistina
+3  A: 

Depending on what language/framework you're using, it may be simpler to put the rewriting/dispatch in the script rather than attempt to do everything in mod_rewrite.

For example, if you were using PHP, given the URL:

http://www.example.com/asdf.php/jkl/id/5/page/2

a script at asf.php could read the PATH_INFO variable, split it on slashes, and write the values into the expected place in $_REQUEST.

Then all you need is one simple rewrite rule to elide the ‘.php’.

bobince
Well that simplifies it quite a bit, thanks! :)
Aistina