Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to redirect 404 (bad urls) to the homepage

I am using asp.net and when I type a bad url manually(in the browser) it gives me:

The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

I want a bad url that doesn't exist to be re-directed to the home page.

How do I do this? I am using sitemap.

like image 801
abbas Avatar asked Feb 22 '11 19:02

abbas


2 Answers

If you have no intentions of letting the users know, they are being redirected. Then, you could just turn custom errors on and do something like this:

<configuration>
  <system.web>
    <customErrors defaultRedirect="default.aspx" mode="On">
      <error statusCode="404" redirect="default.aspx"/>
    </customErrors>
  </system.web>
</configuration>
like image 59
Matt Avatar answered Nov 15 '22 10:11

Matt


As others have already answered, web.config is one way to go.

The other is to catch unhandled exceptions from within your application. This gives you more control of the redirect.

protected void Application_Error(object sender, EventArgs e)
{
    HttpException httpException = Server.GetLastError() as HttpException;
    if (httpException.GetHttpCode() == 404)
       Response.Redirect("/MainPage.aspx");
}

Remember that if you create your own 404-page you must:

  • Add 404-code to the Response manually.
  • Keep the reply body above 512 bytes or the browser will show its default error message instead.
like image 33
Tedd Hansen Avatar answered Nov 15 '22 09:11

Tedd Hansen