Ben J. Boyle
Ben J. Boyle

Reputation: 306

IIS URLRewrite - Multiple Conditions Back Reference in Action URL

Trying to use URLRewrite to set up some redirection but retain some (and only some of the query string parameters from the source UR, but running into some problems.

Essentially I need to keep the Google Analytics UTM parameters and move them to the Action URL. Here's the config section or one of my redirects:

        <rule name="Anything Else" patternSyntax="ECMAScript" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAny" trackAllCaptures="true">
                <add input="{QUERY_STRING}" pattern="utm_source=(\w+)" />
                <add input="{QUERY_STRING}" pattern="utm_medium=(\w+)" />
                <add input="{QUERY_STRING}" pattern="utm_campaign=(\w+)" />
                <add input="{QUERY_STRING}" pattern="utm_term=(\w+)" />
                <add input="{QUERY_STRING}" pattern="utm_content=(\w+)" />
                <add input="{QUERY_STRING}" pattern=".*" />
            </conditions>
            <action type="Redirect" url="https://www.google.com?utm_source={C:1}&amp;utm_medium={C:2}" appendQueryString="false" redirectType="Temporary" />
        </rule>

The query string may contain none, one, or all of the UTM parameters, but I need these rules fir in any case, as long as the original URL matches. To this end, we have the LogicalGrouping set to MatchAny, and the final condition being a complete wildcard. Testing the conditions individually gives me the back references {C:1} through {C:5} for the UTM parameters, and while there are no matching parameters in the source URL, or no more than one, the rules work.

The problem appears when I have multiple matching conditions in the source URL. IIS throws a 500 error "The expression "https://www.google.com? {C:2}" cannot be expanded."

Am I barking up the wrong tree? Is this even possible? I have the option of coding an HTTPHandler and handing the conversion there, but I was hoping to do this without introducing custom code to the server.

Upvotes: 2

Views: 1886

Answers (1)

speyburn
speyburn

Reputation: 65

Within a rule action, you can use the back-references to the last matched condition of that rule. Also within a condition input string, you can use the back-references to the previously matched condition.

With that in mind, a possible way to do what you are trying to do is to use the back-reference from previous condition in the next condition's input:

<conditions>
    <add input="{QUERY_STRING}" pattern="(?:^|&amp;)var1=([1-9]\d+)(?:&amp;|$)" />
    <add input="%{C:1}%_{QUERY_STRING}" pattern="%(.+)%_.*var2=([1-9]\d+)(?:&|$)" />
</conditions>

Then the action of the rule will look like this:

<action type="Redirect" url="newpage.aspx/{C:1}/{C:2}" appendQueryString="false" redirectType="Permanent" />

Upvotes: 5

Related Questions