IIS 7 URL Rewrite Only If No File Nor Subdirectory Nor Query String

iis-7redirectregexrewriteurl

(I posted this question on StackOverflow because searches for an answer showed related questions on StackOverflow, which got answers and many upvotes. But my question so far earned a downvote and an "off-topic" close vote, so I'm trying asking here where it may be considered more on-topic.)

I would like to do a URL rewrite (or redirecton if need be, like in this answered question), except I would like it only to rewrite/redirect if the requested URL is only the site root (with no files or subdirectories and no query strings).

i.e. I want only requests for TheSite.net to rewrite/redirect to TheSite.net/home.htm, but requests for TheSite.net/FAQ.htm or TheSite.net/sub or TheSite.net/?parameter=yep to not be rewritten/redirected.

I have gotten rewrites and redirects to work such as:

<system.webServer>
    <rewrite>
      <rules>
        <clear />
        <rule name="Rewrite home page to Home.htm" stopProcessing="true">
          <match url="^" />
          <action type="Rewrite" url="/Home.htm" />
        </rule>
      </rules>
    </rewrite>
</system.webServer>

I have also tried <match url="^$" /> and <match url="TheSite.net" />, but those naturally rewrite TheSite.net/?parameter=yep too, and I need it to not do that. Perhaps if there is another attribute of <match> which lets me match empty query string but not if there is a query string (or not match if there is anything is after the slash)?

I'm hoping an appropriate rule could do what I wanted, but my RegEx syntax skills are not up to the task and I haven't found an example of something close enough.

On this site, I see IIS URL Rewrite Module Query String Parameters looks like it might be the sort of thing that could work, though what I want is the opposite – to only rewrite if there is no query string or other content after the domain name in the URL.

Best Answer

Ok, subject to complete testing of weird cases, I seem to have found a solution via playing with Conditions, i.e.:

<rule name="Rewrite home page to Home.htm" stopProcessing="true">
  <match url="^$" />
  <conditions>
    <add input="{QUERY_STRING}" pattern=".+=(.+)" negate="true" />
  </conditions>
  <action type="Rewrite" url="/Home.htm" />
</rule>