Lea*_*ing 11 asp.net redirect search-engine http-status-code-301
我正在尝试为网站实现URL重定向,而不是逐页进行.我想在global.asax文件中执行此操作.以下是我定义的代码.
我想将http://website.net作为我的主要网址,如果有人在http://www.website.net中输入,我希望有一个永久的URL重定向.
不幸的是,它不适用于实时网站.任何人都可以指出代码中的问题.代码不会产生任何错误.
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://website.net"))
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace("http://website.net", "http://www.website.net"));
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*nHN 16
主要问题:你正在做上述事情Application_Start- 只执行一次.你应该与每个请求联系起来.试试这个:
void Application_BeginRequest(object sender, EventArgs e)
{
// Code that runs on every request
if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://website.net"))
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace("http://website.net", "http://www.website.net"));
}
}
Run Code Online (Sandbox Code Playgroud)
更好的方法是使用URL重写,可以在Web.Config以下内容中进行配置:
Microsoft重写模块 - 在URL上强制www或从url中删除www
Igo*_*gor 11
如果使用IIS 7或更高版本,最简单的解决方案是使用web.config中的httpRedirect元素.
<httpRedirect enabled="true" exactDestination="true" httpResponseStatus="Permanent">
<add wildcard="/MyOldAspFile.aspx" destination="/MyNewFile.aspx" />
<add wildcard="/MyOldHtmlFile.html" destination="/MyNewFile.aspx" />
</httpRedirect>
Run Code Online (Sandbox Code Playgroud)
此方法非常强大,例如,如果您更改了域但页面相同,则只需添加:
<system.webServer>
<httpRedirect enabled="true" childOnly="true" destination="http://www.mynewdomain.com/" />
</system.webServer>
Run Code Online (Sandbox Code Playgroud)
我在这里写了一篇小文章:ASP.NET 301永久重定向:最佳解决方案
基于以前的正确和有用的答案,这里有几个具体的例子.假设您要删除旧页面(就像我一样),有几个选项.
选项1:修改Global.asax
void Application_BeginRequest(object sender, EventArgs e)
{
// Add permanent redirection for retired pages
if (Request.Url.LocalPath.ToLower().StartsWith("/[OLD PAGE NAME]"))
{
Response.RedirectPermanent("/[NEW PAGE NAME]", false);
}
}
Run Code Online (Sandbox Code Playgroud)
选项2:修改web.config
<system.webServer>
<httpRedirect enabled="true" httpResponseStatus="Permanent">
<add wildcard="/[OLD PAGE NAME]" destination="/[NEW PAGE NAME]" />
</httpRedirect>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25482 次 |
| 最近记录: |