在阅读 Google 网站管理员中心博客(官方博客)上的这篇文章“Slash or not to slash”(链接:http://googlewebmastercentral.blogspot.com/2010/04/to-slash-or-not-to-slash.html)后,我决定测试我的 ASP.NET MVC 应用程序。
例如: http://domain.com/products和 http://domain.com/products/ (以“/”结尾),返回代码200,意思是:谷歌将其理解为两个不同的链接,很可能是“重复内容”。他们建议选择你想要的方式......有或没有破折号并创建一个 301 永久重定向到首选方式。
因此,如果我选择不带破折号,当我尝试访问 http://domain.com/products/ 时它将向不带破折号的链接返回 301:http://domain.com/products .
问题是,我如何使用 ASP.NET MVC 做到这一点?
谢谢, 桂
最佳答案
如果您使用 IIS 7,您可以使用 URL 重写扩展 ScottGu 有一篇关于它的博客文章 here .
或者,如果您想在代码中执行此操作,您可以从 PerRequestTask 继承。这里有一些示例代码从地址中删除了 www - 这是来自 Shrinkr :
public class RemoveWww : PerRequestTask
{
protected override TaskContinuation ExecuteCore(PerRequestExecutionContext executionContext)
{
const string Prefix = "http://www.";
Check.Argument.IsNotNull(executionContext, "executionContext");
HttpContextBase httpContext = executionContext.HttpContext;
string url = httpContext.Request.Url.ToString();
bool startsWith3W = url.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase);
bool shouldContinue = true;
if (startsWith3W)
{
string newUrl = "http://" + url.Substring(Prefix.Length);
HttpResponseBase response = httpContext.Response;
response.StatusCode = (int) HttpStatusCode.MovedPermanently;
response.Status = "301 Moved Permanently";
response.RedirectLocation = newUrl;
response.SuppressContent = true;
response.End();
shouldContinue = false;
}
return shouldContinue ? TaskContinuation.Continue : TaskContinuation.Break;
}
}
您只需要在您的代码中检查以/结尾的 url。
** 请注意,这确实使用了第 3 方 dll - System.Web.MVC.Extensibility 命名空间。 **
关于asp.net - SEO:带有和不带有破折号 "/"和 ASP.NET MVC 的重复 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2755126/