1
votes

I need 301 redirect for all urls like

xyz.com/searchitems?key1=val1&key2=val2 to be like

xyz.com/searchitems

i.e. I want query string to be removed from URL. I have written this so far in my web.config

        <rewrite>
      <rules>
        <rule name="Rewrite to searchitems">
          <match url="^searchitems?$" />
<conditions>
    <add input="{QUERY_STRING}" pattern="(.*)" />
  </conditions>
          <action type="Redirect" redirectType="Permanent" url="{R:0}" appendQueryString="false"  />
        </rule>
      </rules>
   </rewrite>

but it is making redirect loop

Edit:

I wat the querystring to be removed just for this url "xyz.com/searchitems" and not for all urls. There can be any number of query string params in urls.

1
"?" needs to be escaped in regular expressions. Currently, your rule matches the URL "searchitem" since the trailing "s" is turned optional by the "?". If the "?" had been a literal part of the URL, maybe there wouldn't be a redirect loop since the resulting URL has no "?" in it. :) - bzlm
I tried this too <match url="^searchresults$" /> - Rocky Singh
I guess the pattern to match searchresults only with some params is "^(.*searchitems)\?.+$" - Sbu
It is not even matching now and just opening xyz.com/searchitems?key1=val1&key2=val2 - Rocky Singh
Unit test it with something like this : Regex r = new Regex(@"^(.*searchitems)\?.+$"); var b1 = r.IsMatch("xyz.com/searchitems?qsdfj=qsdkfj%20"); var b2 = r.IsMatch("xyz.com/searchitems?key1=val1&key2=val2"); var b3 = r.IsMatch("xyz.com/searchitems"); var b4 = r.Matches("xyz.com/searchitems?qsdfj=qsdkfj%20"); - Sbu

1 Answers

2
votes

Try this:

  <rewrite>
      <rules>
        <rule name="Custom rule" stopProcessing="true">
          <match url="^searchitems" />
          <conditions>
            <add input="{QUERY_STRING}" pattern="(.+)" />
          </conditions>
          <action type="Redirect" url="/searchitems" appendQueryString="false" />
        </rule>
      </rules>
    </rewrite>