Forum Moderators: phranque

Message Too Old, No Replies

Rewrite Problem with Query String

Rewrite query_string

         

Gissit

5:17 pm on Dec 31, 2007 (gmt 0)

10+ Year Member



Hi
I have been trying to get a rewrite in htaccess working and can't see the wood for the trees.

What I am trying to do is to to rewrite example.php?page=111 to stuff.php?parent_id=50&page=111
Where page is a number from 1 to 100

Jim on here kindly gave me an example that I think has lead me in the right direction but I can't get it to work. The example he gave was

RewriteCond %{HTTP_QUERY_STRING} ^(page=[^&]+)$ 
RewriteRule ^example\.php$ /stuff.php?parent_id=50&%1 [L]

There are a couple of things I did not understand with this such as the ^& and the %1. I did not try it at the time as I was tied up at my day job and it seemed a bit late to rply to the original thread. Anyway when I tried it I had no luck with it and so did a bit of reading and came up with the following.

RewriteCond %{HTTP_QUERY_STRING} ^(page=[0-9]+)$ 
RewriteRule ^example.php$ stuff.php?parent_id=50&$1 [L]

This does not work either and I can't see why. I'm sure I have misunderstood the syntax. When I typre a url such as [somesite.com...] I get a 404 error as the rule does not appear to be triggered at all.

jdMorgan

8:38 pm on Dec 31, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



How about:

RewriteCond %{[b]QUERY_STRING[/b]} ^(page=[0-9]+)$
RewriteRule ^example\.php$ stuff.php?parent_id=50[b]&%1[/b] [L]

"[^&]+" means "one or more characters not equal to an ampersand" or equivalently, "at least one, and all characters up until you find the next ampersand or the end of the string." This would 'find' the end of each name/value pair in a query string that contained multiple name/value pairs. It would also allow those name/value pairs to contain any characters -- except "&" of course.

"$1" refers to the contents of the first matched parenthesized subpattern in the RewriteRule pattern.
"%1" refers to the contents of the first matched parenthesized subpattern in the last-matched RewriteCond pattern.

For more information, see the documents cited in our forum charter [webmasterworld.com] and the tutorials in the Apache forum section of the WebmasterWorld library [webmasterworld.com].

Jim

Gissit

8:59 pm on Dec 31, 2007 (gmt 0)

10+ Year Member



Jim
Thank you very much for that, it is working now. I really appreciate the description as well as the solution as I really do not like to ask direct questions as I can usually find myself answers online. I didn't sppreciate that the regular expression syntax was different in different places (I thought ^ always meant 'starting here') and I really like your original method now I understand it as it can cope with a wider range of situations.

I never even thought to look in the forum charter but I have spent more than a couple of hours reading search engine results before posting the question.

Once again many thanks.
Brian