how to redirect 404 (bad urls) to the homepage

a 夏天 提交于 2019-12-05 18:41:08
Matt

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>

Add this section to your web.config:

<customErrors mode="On" defaultRedirect="{yourDefaultErrorPage}">
    <error statusCode="404" redirect="{yourhomePage}"/>
</customErrors>

customErrors Element on MSDN.

If you can, try have your 404 pages permanent redirect to a similar URL.

So instead of 404 response, make a 301 response to a similar URL on your site. Best SEO wise

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!