2
A
回答
5
protected void Application_BeginRequest(object sender, EventArgs e)
{
// Do Not Allow URL to end in trailing slash
string url = HttpContext.Current.Request.Url.AbsolutePath;
if (string.IsNullOrEmpty(url)) return;
string lastChar = url[url.Length-1].ToString();
if (lastChar == "/" || lastChar == "\\")
{
url = url.Substring(0, url.Length - 1);
Response.Clear();
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", url);
Response.End();
}
}
+2
如果你在localhost中测试,确保使用if(string.IsNullOrEmpty(url)|| url.Length == 1)return;这是因为第一个url只是“/” – danpop 2012-12-20 12:47:32
0
使用的HttpContext.Current.Request
扩展方法使得这种可重复使用其他类似的问题,如重新定向,以避免重复内容的网址为第1页:
public static class HttpRequestExtensions
{
public static String RemoveTrailingChars(this HttpRequest request, int charsToRemove)
{
// Reconstruct the url including any query string parameters
String url = (request.Url.Scheme + "://" + request.Url.Authority + request.Url.AbsolutePath);
return (url.Length > charsToRemove ? url.Substring(0, url.Length - charsToRemove) : url) + request.Url.Query;
}
}
这可以被称为需要:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
String requestedUrl = HttpContext.Current.Request.Url.AbsolutePath;
// If url ends with /1 we're a page 1, and don't need (shouldn't have) the page number
if (requestedUrl.EndsWith("/1"))
Response.RedirectPermanent(Request.RemoveTrailingChars(2));
// If url ends with/redirect to the URL without the/
if (requestedUrl.EndsWith("/") && requestedUrl.Length > 1)
Response.RedirectPermanent(Request.RemoveTrailingChars(1));
}
相关问题
- 1. 从URL中删除拖尾斜杠
- 2. Htaccess重写删除尾部斜杠
- 3. IIS重写规则删除斜杠
- 4. htaccess删除尾部斜杠
- 5. 删除尾部斜杠htaccess
- 6. IIS 7.5:删除尾部斜杠不起作用
- 7. Nginx重写无尾斜杠
- 8. 重写文件夹并删除末尾的斜杠
- 9. Apache URL重写 - 删除仅从基址的尾部斜杠
- 10. 的mod_rewrite删除尾随斜杠Laravel
- 11. 用htaccess删除尾部斜杠
- 12. 用mod_rewrite删除尾部斜杠
- 13. 添加尾部斜杠并删除.htaccess
- 14. SharePoint删除URL中的尾部斜杠
- 15. 从批处理文件输入中删除拖尾斜杠
- 16. 删除Wordpress slug的尾部斜杠
- 17. 使用mod_rewrite重写斜杠
- 18. 的.htaccess重写部队尾随斜杠
- 19. 重写规则没有结尾斜杠?
- 20. 重写没有结尾斜杠的URL?
- 21. .htaccess文件Mod_rewrite - 删除扩展名并删除尾部斜杠
- 22. 在Mod_rewrite中添加拖尾斜杠并在虚拟目录中重定向非拖尾斜杠
- 23. RewriteRule删除所有斜杠
- 24. 拖尾斜杠开头的www
- 25. 删除反斜杠
- 26. IIS URL重写强制执行尾随正向斜杠404不工作404
- 27. 在url结尾处删除尾部斜杠
- 28. Bootstrap:breadcrumb删除斜杠?
- 29. mod删除尾部斜杠不起作用
- 30. htaccess - URL重写 - 删除斜杠,但不是从文件
有趣的是,如果你在这里搜索“url trailing slash”(在右上角的搜索框中输入,没有引号),一半的人想删除斜线,一半的人w蚂蚁添加它。 – DOK 2012-01-31 16:20:36