Forum Moderators: phranque

Message Too Old, No Replies

Backreference with more than a rewritecond

         

moroandrea

4:54 pm on Nov 16, 2010 (gmt 0)

10+ Year Member



Hi all

It's about a couple of hours that I'm really scratching my head on the wall trying to understand how to pass a backreference to the rewrited URL where more that one RewriteCond exist.

A quick example just to let you understand what I want to achieve

RewriteCond %{HTTP_HOST} ^(www\.)?test\.(.*)(\.|\.?:[0-9]+)?$ [NC]
RewriteCond $1^(beauty_eyes|beauty_eyes_definer)$
RewriteRule ^/[^/]+/[^/.]+/[^/.]+/(.*)$http://%2.test.com/store/beauty-fragrance/eyes[L]

If I do something like above, the rewritelog I create let me see that the %2 doesn't contain anything

However, if I remove the second RewriteCond and leave something like this

RewriteCond %{HTTP_HOST} ^(www\.)?test\.(.*)(\.|\.?:[0-9]+)?$ [NC]
RewriteRule ^/[^/]+/[^/.]+/[^/.]+/(.*)$http://%2.test.com/store/beauty-fragrance/eyes[L]

Everything works fine, well at least the %2 contains a value, but I wish I could use the first example because I have more than one value ($1) that must be checked.

Is this possible?

Many thanks

jdMorgan

9:28 pm on Nov 17, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The problem is that, as documented, only the back-references created by the *last-matched* RewriteCond are available. This is for good reason, as it allows later RewriteConds to back-reference earlier ones, but does present some difficulties, as you have found.

There are numerous ways around it: Combine RewriteCond tests onto one line by testing more than one variable per RewriteCond, re-order the RewriteConds so that the last Condition matched is the one that creates the back-reference(s) that you need, create and use 'user-defined variables' (see RewriteRule "E=" flag), or, as in this case, simplify the code by doing the required pattern match in the RewriteRule itself:

RewriteCond %{HTTP_HOST} ^(www\.)?test(\.[^.]+)+(\.|\.?:[0-9]+)?$ [NC]
RewriteRule ^/[^/]+/[^/.]+/[^/.]+/(beauty_eyes(_definer)?)$ http://$1.test.com/store/beauty-fragrance/eyes [R=301,L]

Note the many minor changes to this rule. Some are subtle, but all are important.

Jim