views:

35

answers:

2

I know something's conflicting but being a mod rewrite Muggle it's time to ask for help.

I am re-writing http://test.com/[name]/
to http://test.com/script.php?id=[name]
with success, using:

(rule#1)
RewriteRule ^(.*)\/$ script.php?id=$1&%{QUERY_STRING} [L]

Next, I rewrite http://test.com/[name]/foobar/[key]
to http://test.com/script.php?id=[name]&foobar=[key]
also with success, using:

(rule#2)
RewriteRule ^(.*)\/foobar/([0-9]+)$ script.php?id=$1&foobar=$2 [L]

However, when I try to include the query strings,
so that http://test.com/[name]/foobar/[key]?p=[page]
could be re-written to http://test.com/script.php?id=[name]&foobar=[key]&p=[page]
with this:

(rule#3)
RewriteRule ^(.*)\/foobar/([0-9]+)$ script.php?id=$1&foobar=$2&%{QUERY_STRING} [L]

then Apache just throws me back to http://test.com/script.php.

I know from trial and error that rule#3 would work if it did not use the same script.php as rule#1,
but I have no idea how to fix it, so any help appreciated!

Arrgh..after double-checking my rules with Gumbo's examples, I finally found out what went wrong. Although not perfect, my rewrite rules were actually working as intended. However I totally forget that I had another script that checks for valid parameters... apparently, throwing random test values, sometimes is not a good idea. Thanks for the ^/ trick though!

A: 

Warning: you are using .*, which can actually match nothing. Use .+ unless it's your intent to match nothing.

Have all your rules been listed here? Are there any errors in your error_log regarding this?

Lekensteyn
+2  A: 

Use [^/]+ to match only one or more arbitrary characters except / instead of .* any number of arbitrary characters:

RewriteRule ^([^/]+)/$ script.php?id=$1&%{QUERY_STRING} [L]
RewriteRule ^([^/]+)/foobar/([0-9]+)$ script.php?id=$1&foobar=$2 [L]

Additionally, you can set the QSA flag to have the original requested query automatically appended to the new URL instead of appending it manually:

RewriteRule ^([^/]+)/$ script.php?id=$1 [L,QSA]
Gumbo