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. Descrip开发者_StackOverflow社区tion: 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.
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>
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.
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
精彩评论