Redirecting default.aspx to root virtual directory Redirecting default.aspx to root virtual directory asp.net asp.net

Redirecting default.aspx to root virtual directory


The above code will work fine as long as you dont have a sub-directory. AFAIK, its a bug in ASP.NET: the Request.RawUrl should NOT contain "/default.aspx" when the URL does not have that extension. I have tested your code and it works fine without a sub directory, but if default.aspx is under a directory, the Request.RawUrl object fails to get rid of default.aspx and hence the infinite loop.


Slight modifications to handle subdirectories and maintain url variables. Better comparison and replace functionality probably exists, but this works for me with IIS 7.

if (Request.RawUrl.ToLower().Contains("/default.aspx"))  // use Contains instead of EndsWith to handle url vars{    string newUrl = string.Format("{0}://{1}{2}",                    Request.Url.Scheme,                    Request.Url.Authority,                    Request.RawUrl.ToLower().Replace("default.aspx", ""));  // don't remove the trailing slash so url vars are maintained    Response.Clear();    Response.Status = "301 Moved Permanently";    Response.AddHeader("Location", newUrl);    Response.End();}


I tried the URL Rewrite method. I.e. this one:

    <rule name="default page" stopProcessing="true">      <match url="^default\.aspx$" />      <action type="Redirect" url="{R:0}" redirectType="Permanent" />    </rule>

but it sent my browser in an infinite redirect loop. I amended it to the following and it worked fine:

            <rule name="default page" stopProcessing="true">                <match url="(.*)default.aspx$" />                <action type="Redirect" url="{R:1}" redirectType="Permanent" />            </rule>