how to redirect 404 (bad urls) to the homepage

懵懂的女人 提交于 2020-02-02 04:20:21

问题


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.


回答1:


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>



回答2:


Add this section to your web.config:

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

customErrors Element on MSDN.




回答3:


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




回答4:


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.


来源:https://stackoverflow.com/questions/5082662/how-to-redirect-404-bad-urls-to-the-homepage

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