ASP.NET下用URLRewriter重寫二級域名
這里要求對域名進行重寫,實現http://1234.abc.com/ 到 ~/Defa.aspx?id=1234的重寫。
第一:域名
首先域名要支持泛解悉,就是域名解悉的主機名為星號*,例:*.abc.com。如下圖
這樣能保證你在瀏覽器地址欄輸入任何前綴,DNS都會把它們指向到你指定的IP地址上。
第二:IIS設置(Win2003 + IIS 6為例)
(1)網站必須為Web服務器的默認站點,即端口號為80,主機頭為空的站點。如下圖所示。
該站點接收所有對該服務器的HTTP請求(其它設置為主機頭的站點除外)。所以任何二級域名訪問該服務器都會由該站點進行處理。
(2)另外要在站點的“通配符應用程序映射”列表中添加ASP.NET的Web請求處理程序aspnet_isapi.dll。如下圖所示。
在這里的設置,是讓該站點接到的所有請求都交給aspnet_isapi.dll處理。
第三:修改Microsoft的URLRewriter。
運行開源項目URLRewriter。這里需要修改兩個地方:
(1)BaseModuleRewriter.cs類
{
HttpApplication app = (HttpApplication) sender;
//Rewrite(app.Request.Path, app);
Rewrite(app.Request.Url.AbsoluteUri, app); // ## ## ## 這里修改了
}
這里將app.Request.Path 替換成了 app.Request.Url.AbsoluteUri
(2)ModuleRewriter.cs類
2. {
3. // log information to the Trace object.
4. app.Context.Trace.Write("ModuleRewriter", "Entering ModuleRewriter");
5. // get the configuration rules
6. RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;
7. // iterate through each rule...
8. for (int i = 0; i < rules.Count; i++)
9. {
10. // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
11. //string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].LookFor) + "$";
12. string lookFor = "^" + rules[i].LookFor + "$"; // ## ## ## 這里修改了
13. // Create a regex (note that IgnoreCase is set...)
14. Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);
15. // See if a match is found
16. if (re.IsMatch(requestedPath))
17. {
18. // match found - do any replacement needed
19. string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, rules[i].SendTo));
20. // log rewriting information to the Trace object
21. app.Context.Trace.Write("ModuleRewriter", "Rewriting URL to " + sendToUrl);
22. // Rewrite the URL
23. RewriterUtils.RewriteUrl(app.Context, sendToUrl);
24. break; // exit the for loop
25. }
26. }
27. // Log information to the Trace object
28. app.Context.Trace.Write("ModuleRewriter", "Exiting ModuleRewriter");
29. }
這里將string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].LookFor) + "$";
改成了 string lookFor = "^" + rules[i].LookFor + "$";
這兩個地方修改完以后,生成項目。將項止目bin/Debug目錄下的URLRewriter.dll文件Copy到我們要重寫URL的項目中。
第四:配置項目
(1)在web.config文件的configSections節點下添加如下一行代碼
這里配置一個重寫配置的類
(2)修改httpModules節點,在里面添加一行配置代碼
(3)在主節點configuration節點下添加路由規則,代碼如下:
2. <RewriterConfig>
3. <Rules>
4. <RewriterRule>
5. <LookFor>http://(\w+).abc.com/</LookFor>
6. <SendTo>~/Defa.aspx?id=$1</SendTo>
7. </RewriterRule>
8. </Rules>
9. </RewriterConfig>
10. <!-- URL重寫 將捕獲頁面轉發到實際地址 ( 結束 ) -->
代碼里一個RewriterRule節點就是一個規則,這時只有一個,即把域名中的主機頭部分做為Defa.aspx頁面的id參數的值發送給Defa.aspx頁面。
注意:這里LookFor節點里的http://(\w+).abc.com/不能少了最后的反斜框
OK,一切完工
發布,上傳到服務器,測試一下,如圖
本次測試需要一個類庫:URLRewriter.dll (測試版本 1.0.1495.18710)