/// <summary> /// Rewrite the URL if it matches any of the URL rewrite rules. /// </summary> /// <param name="args">HttpRequest pipeline arguments.</param> private void RewriteUrl(HttpRequestArgs args) { if (!urlRewriteRulesCache.Any()) { return; } // Prepare flags to retrieve the URL strings from Uri objects. var componentsWithoutQuery = UriComponents.Scheme | UriComponents.Host | UriComponents.Path; var componentsWithQuery = componentsWithoutQuery | UriComponents.Query; Uri requestUrl = args.Context.Request.Url; // If we found a matching URL rewrite rule for the request URL including its querystring, // we will rewrite to the exact target URL and dispose the request querystring. // Otherwise, if we found a match for the request URL without its querystring, // we will rewrite the URL and preserve the querystring from the request. bool preserveQueryString = false; // Use the request URL including the querystring to find a matching URL rewrite rule. UrlRewriteRule rule = urlRewriteRulesCache .Where(x => x != null) .FirstOrDefault(x => this.EqualUrl(x.GetSourceUrl(requestUrl), requestUrl, componentsWithQuery)); if (rule == null) { // No match was found, try to find a match for the URL without querystring. rule = urlRewriteRulesCache .Where(x => x != null) .FirstOrDefault(x => this.EqualUrl(x.GetSourceUrl(requestUrl), requestUrl, componentsWithoutQuery)); preserveQueryString = rule != null; } if (rule == null) { // No matching rewrite rule was found. return; } // Set the target URL with or without the original request's querystring. string targetUrl = preserveQueryString ? string.Concat(rule.GetTargetUrl(requestUrl).GetComponents(componentsWithoutQuery, UriFormat.Unescaped), requestUrl.Query) : rule.GetTargetUrl(requestUrl).GetComponents(componentsWithQuery, UriFormat.Unescaped); if (Settings.LogRewrites) { // Write an entry to the Sitecore log informing about the rewrite. Logging.LogInfo(string.Format("URL rewrite rule '{0}' caused the requested URL '{1}' to be rewritten to '{2}'", rule.ItemId, requestUrl.AbsoluteUri, targetUrl), this); } // Return a permanent redirect to the target URL. this.Redirect(targetUrl, args.Context); }
/// <summary> /// Add a rewrite rule from Sitecore to the cache. /// </summary> /// <param name="rewriteRuleItem"></param> private void AddRewriteRule(Item rewriteRuleItem) { // Convert the rewrite rule item to a model object and add to the cache. if (rewriteRuleItem.TemplateID.Equals(ItemIds.Templates.UrlRewriteRule)) { // Add a URL rewrite rule. var rule = new UrlRewriteRule(rewriteRuleItem); if (rule.Validate()) { urlRewriteRulesCache.Add(rule); } } else if (rewriteRuleItem.TemplateID.Equals(ItemIds.Templates.HostNameRewriteRule)) { // Add a hostname rewrite rule. var rule = new HostNameRewriteRule(rewriteRuleItem); if (rule.Validate()) { hostNameRewriteRulesCache.Add(rule); } } }