htaccess url regex display “&” if backreference is matched

By : cori
Source: Stackoverflow.com
Question!

I'm using IsapiRewriter on IIS6, but I think this question is more general than that. I'm also pretty sure there's no way to do it, but decided I should ask folks who know more regex than I do before giving up completely.

I'm matching url tails like the following:

^/term1(\?)?(.*)

which successfully matches

http://domain.tld/term1?utm=1234

and when used in a pattern like

^/term1(\?)?(.*)   /term1handler.aspx$1$2 [I]

quite properly redirects

http://domain.tld/term1?utm=1234

to

http://domain.tld/term1handler.aspx?utm=1234

However, some of my redirections need to redirect to something with a query string parameter already in the output. The existing redirect looks like

^/term1   /term1handler.aspx?ID=12345 [I]

I'd like to find a solution that allows me to replace $1 with an ampersand if there's a match there so that I end up with

http://domain.tld/term1handler.aspx?ID=12345&utm=1234

Is there a regex pattern that can do this?

By : cori


Answers

Your rule should be using %{QUERY_STRING} and must use QSA flag in RewriteFlag like this:

RewriteCond %{QUERY_STRING} ^(utm=.*)$
RewriteRule ^term1/?$ term1handler.aspx?%1 [R,L,QSA,NE]

QSA flag will make sure to append utm=1234 query parameter with additional query parameter ID=12345 thus making a composite REQUEST_URI like /term1handler.aspx?ID=12345

By : anubhava


This video can help you solving your question :)
By: admin