Dan Price Dan Price - 4 months ago 41
ASP.NET (C#) Question

IIS Redirect not working without trailing slash

I have a web app that I'm decommissioning and I'm trying to redirect all requests to the old app to a particular page (which shows a link to the replacement and a message advising users to update their bookmarks).

I've set up a HTTP Redirect in the web.config using the answer from this question: ASP.NET httpRedirect : redirect all pages except one and it works except for when the user enters the URL of the site's root folder omitting the trailing slash, in which case it goes to the next directory up the tree, for example:

Original site root:

[domain]/foo/bar/


[domain]/foo/bar/specificpage.aspx
redirects to
[domain]/foo/bar/Default.aspx
(OK)

[domain]/foo/bar/
redirects to
[domain]/foo/bar/Default.aspx
(OK)

[domain]/foo/bar
redirects to
[domain]/foo/Default.aspx
(not OK)

Here's the relevant web.config:

<system.webServer>
<httpRedirect enabled="true" destination="~/Default.aspx" httpResponseStatus="Permanent">
<add wildcard="/" destination="Default.aspx" />
</httpRedirect>
</system.webServer>
<location path="Default.aspx">
<system.webServer>
<httpRedirect enabled="false" />
</system.webServer>
</location>


How can I get it to work when the user goes to
[domain]/foo/bar
?

Answer

For the record, I fixed this by setting the redirect URL to the absolute path of the file, including the virtual directory the site root sits in:

<system.webServer>
    <httpRedirect enabled="true" destination="/foo/bar/Default.aspx" httpResponseStatus="Permanent" exactDestination="true">
      <add wildcard="/" destination="Default.aspx" />
    </httpRedirect>
  </system.webServer>
  <location path="Default.aspx">
    <system.webServer>
      <httpRedirect enabled="false" />
    </system.webServer>
  </location>
Comments