Init(HttpApplication app) {///**********************************************************************************/// Author:活靶子,huobazi/// Date:2005-08-18/// Description:增加BeginRequest,在内增加防止黑客可能利用的某些Url漏洞攻击的代码///**********************************************************************************app.BeginRequest += new EventHandler(this.RewriterModule_BeginRequest);// 警告!此代码不适用于 Windows 身份验证!// 如果使用 Windows 身份验证,// 请改为 app.BeginRequestapp.AuthorizeRequest += new EventHandler(this.RewriterModule_AuthorizeRequest);}
protected virtual void RewriterModule_BeginRequest(object o , EventArgs e){HttpApplication app = ((HttpApplication)(o)); HttpServerUtility Server = app.Server; HttpRequest Request = app.Request; ///************************************************************/// Author:活靶子,huobazi/// Date:2005-08-18/// Description:修补黑客可能采用".."的方法进入其他目录的问题///************************************************************string strURL = Server.UrlDecode(Request.RawUrl); if (strURL.IndexOf("..") != -1) { throw new HttpException(404, "Not Found"); } ///**********************************************************************************/// Author:活靶子,huobazi/// Date:2005-08-18/// Description:修补"规范化"问题 see: http://support.microsoft.com/?kbid=887459///***********************************************************************************if (Request.Path.IndexOf(''\\'') >= 0 ||Path.GetFullPath(Request.PhysicalPath) != Request.PhysicalPath) {throw new HttpException(404, "Not Found");}}
三。开始匹配域名
protected void Rewrite(string requestedPath, System.Web.HttpApplication app){string host = app.Context.Request.Url.Host.ToString().ToLower();app.Context.Trace.Write("RewriterModule", "Entering ModuleRewriter"); RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules; for(int i = 0; i < rules.Count; i++){//将MulitDomain.config内定义的规则LookFor的值逐个匹配当前主机名判断否被定义了需要重写//如果匹配则需要重写,那将请求重写到SendTo定义的目录内的该文件string lookFor = "^" + rules[i].LookFor + "$";//string lookFor = "^" + Rewriter.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].LookFor + requestedPath) + "$";Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);if (re.IsMatch(host)){string sendToUrl = Rewriter.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].SendTo + requestedPath);app.Context.Trace.Write("RewriterModule", "Rewriting URL to " + sendToUrl);Rewriter.RewriteUrl(app.Context, sendToUrl);break;}} app.Context.Trace.Write("RewriterModule", "Exiting ModuleRewriter");}
四。写规则文件
MulitDomain.config的匹配规则如下:
<?xml version="1.0" encoding="utf-8" ?>
<RewriterConfig>
<Rules>
<RewriterRule>
<LookFor>www\.xaradio\.com</LookFor>
<SendTo>~/xaradio</SendTo>
</RewriterRule>
<RewriterRule>
&n