Lars Holdgaard
Lars Holdgaard

Reputation: 9986

Remove querystring through web.config

On my website, I have a situation where my URL sometimes get a querystring parameter appended by a system outsite ours.

So instead of looking like this: http://www.domain.com?myquery=blah or http://www.domain.com, it has the url http: http://www.domain.com?myquery=blah&theirpara=blah or http://www.domain.com?theirpara=blah .

When a user visits with the "theirpara" parameter, I would like to make a 301 redirect to the URL without it.

I've tried using the URL rewrite module, but not really getting anywhere. It would be nice to do it at IIS/web.config level instead of Response.RedirectPermanent if possible.

I thought it would be good to setup up using a rule (URL write module), but to be honest, I've no idea how to fix this issue. I am using the following rule to remove the trailing slash, but not sure how to modify it to this need.

<!--To always remove trailing slash from the URL-->
<rule name="Remove trailing slash" stopProcessing="true">
  <match url="(.*)/$" />
  <conditions>
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
  </conditions>
  <action type="Redirect" redirectType="Permanent" url="{R:1}" />
</rule>

Any ideas on how to set it up?

Upvotes: 2

Views: 4767

Answers (2)

Daniel Calliess
Daniel Calliess

Reputation: 853

I don't have an IIS to hand but the following should be working:

Change match to

<match url="(.*)&theirpara=blah(.*)" />

and redirect to

<action type="Redirect" redirectType="Permanent" url="{R:1}{R:2}" />

If you want it to work not only on the plain domain you should remove the conditions accordingly.

Upvotes: 1

strmstn
strmstn

Reputation: 872

If you are looking for a pretty generic rule that removes theirpara but keeps any other query string parameters then you will have to handle cases where

  1. It is alone: ?theirpara=123 -> /
  2. It is first: ?theirpara=123&ourparams=456 -> ?ourparams=456
  3. It is in the middle: ?our1=123&theirpara=456&our2=789 -> ?our1=123&our2=789
  4. It is last: ?ourparams=123&theirpara=456 -> ?ourparams=123

I wrote a rule that handles these cases but in case 4 a trailing ampersand is left, I hope it is enough to get you started though.

<rule name="Redirect on theirpara" stopProcessing="true">
    <match url="^(.*)$" />
        <conditions>
            <add input="{QUERY_STRING}" pattern="^(.*)theirpara=([^=&amp;]+)&amp;?(.*)$" />
        </conditions>
    <action type="Redirect" url="/{R:0}?{C:1}{C:3}" appendQueryString="false" />
</rule>

Upvotes: 5

Related Questions