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. Nginx重寫無尾斜槓
- 6. Apache URL重寫 - 刪除僅從基址的尾部斜槓
- 7. 用mod_rewrite刪除尾部斜槓
- 8. SharePoint刪除URL中的尾部斜槓
- 9. 從批處理文件輸入中刪除拖尾斜槓
- 10. 使用mod_rewrite重寫斜槓
- 11. .htaccess文件Mod_rewrite - 刪除擴展名並刪除尾部斜槓
- 12. 在Mod_rewrite中添加拖尾斜槓並在虛擬目錄中重定向非拖尾斜槓
- 13. 拖尾斜槓開頭的www
- 14. 刪除反斜槓
- 15. 在url結尾處刪除尾部斜槓
- 16. mod刪除尾部斜槓不起作用
- 17. 在WordPress中使用.htaccess刪除尾部斜槓
- 18. 在子目錄中使用.htaccess刪除尾部斜槓
- 19. htaccess尾斜槓
- 20. .htaccess - 刪除www,強制https,刪除php並刪除尾部斜槓
- 21. 用正斜槓重寫.htaccess
- 22. 禁用鏈接被刪除開始斜槓重寫
- 23. URL斜槓被刪除
- 24. TinyMCE刪除雙斜槓
- 25. mod_rewrite:刪除尾部斜槓(只有一個!)
- 26. 從nginx的$ uri中刪除尾部斜槓?
- 27. 如果不存在,則包含尾隨斜槓的URL重寫
- 28. 刪除WP多站點.htaccess文件中的尾部斜槓
- 29. 使用SED刪除包含斜槓線/
- 30. 如何使用javascript刪除正斜槓
有趣的是,如果你在這裏搜索「url trailing slash」(在右上角的搜索框中輸入,沒有引號),一半的人想刪除斜線,一半的人w螞蟻添加它。 – DOK 2012-01-31 16:20:36