views:

151

answers:

3

I have a problem that I cannot wrap my head around.

I'm using Apache and PHP

I need to get:

http://localhost.com/cat_ap.php?nid=5964

from

http://localhost.com/cat_ap~nid~5964.htm

How do I go about changing that around? I have done more simple mod rewrites but this is slightly more complicated. Can anyone give me a leg up or point me in the right direction

+4  A: 
RewriteRule ^/cat_ap~nid~(.*)\.htm$ /cat_ap?nid=$1 [R]

The [R] at the end is optional. If you omit it, Apache won't redirect your users (it will still serve the correct page).

If the nid part is also a variable, you can try this:

RewriteRule ^/cat_ap~([^~]+)~(.*)\.htm$ /cat_ap?$1=$2 [R]

EDIT: As Ben Blank said in his comment, you might want to restrict the set of valid URLs. For example, you might want to make sure a nid exists, and that it's numerical:

RewriteRule ^/cat_ap~nid~([0-9]+)\.htm$ /cat_ap?nid=$1

or if the nid part is a variable, that it only consists of alphabetical characters:

RewriteRule ^/cat_ap~([A-Za-z]+)~([0-9]+)\.htm$ /cat_ap?$1=$2
Can Berk Güder
You may wish to restrict which characters are matched (see the comments on kristina's answer). For example, if your IDs are always numeric, try using ([0-9]+) instead of (.*).
Ben Blank
Yeah, I made the comment on kristina's answer. =) I thought about editing my answer, but the question doesn't state such a requirement. Either way, I'll edit my answer for the sake of reference.
Can Berk Güder
+1  A: 

Assuming the variable parts here are the "nid" and the 5964, you can do:

RewriteRule ^/cat_ap~(.+)~(.+).htm$ ^/cat_ap?$1=$2

The first "(.+)" matches "nid" and the second matches "5964".

kristina
I'm not sure that's gonna work, wouldn't it also match /cat_ap~nid~foo~5964.htm ?
Can Berk Güder
I agree. The dots there should probably be negated character classes instead (e.g. [^~]).
Ben Blank
You are both totally right, negated character classes would be much better.
kristina
A: 

If you want everything arbitrary:

RewriteRule ^/(\w+)~(\w+)~(\w+)\.htm$ $1?$2=$3 [L]

Where \w is equal to [A-Za-z0-9_]. And if you want to use this rule in a .htaccess file, remove the leading / from the pattern.

Gumbo