Wednesday, April 13, 2011

How to Use RewriteCond BackReferencing %N

I have the following rules in my httpd.conf

   RewriteEngine on
       RewriteBase /
       RewriteCond %{QUERY_STRING} password=* 
       RewriteCond %{QUERY_STRING} bi2=(.*) 
       RewriteCond %{REQUEST_URI}  /myGet.php(.*)$
       RewriteRule ^(.*)$  http://blog.myexample%1.com/$1

However, when I executed the Request URI

/myGet.php?password=john&bi2=67

I was redirected to

http://blog.myexample.com/myGet.php?password=john&bi2=67

instead of

http://blog.myexample67.com/myGet.php?password=john&bi2=67

It seems that %N for the RewriteCond BackReferencing is not working. Although $N is.

From stackoverflow
  • Alter the order or the RewriteCond directives so that the last directive is the one you want the information from:

    RewriteCond %{QUERY_STRING} password=* 
    RewriteCond %{REQUEST_URI}  /myGet.php(.*)$
    RewriteCond %{QUERY_STRING} bi2=(.*)
    RewriteRule ^(.*)$  http://blog.myexample%1.com/$1
    

    But I rather suggest:

    RewriteCond %{QUERY_STRING} password=
    RewriteCond %{QUERY_STRING} bi2=([^&]*)
    RewriteRule ^/myGet\.php.*$  http://blog.myexample%1.com$0
    
    Ngu Soon Hui : Hmm, not sure whether this kind of reordering does any good or not.. what if I need to get the second last %2 backreferencing value?
    Gumbo : There is no other way to do this. Or at least: I don’t know any other way to do this. If you need the “password” too, you have to use some tricks to carry the value along the RewriteCond directives or combine them into one expression.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.