コード例 #1
0
        /// <summary>
        /// Rewrite the hostname if it matches any of the hostname rewrite rules.
        /// The requested path and querystring is kept intact, only the hostname is rewritten.
        /// </summary>
        /// <param name="args">HttpRequest pipeline arguments.</param>
        private void RewriteHostName(HttpRequestArgs args)
        {
            if (!hostNameRewriteRulesCache.Any())
            {
                return;
            }

            // Extract the hostname from the request URL.
            Uri    requestUrl = args.Context.Request.Url;
            string hostName   = requestUrl.Host;

            // Check if there is a hostname rewrite rule that matches the requested hostname.
            HostNameRewriteRule rule = hostNameRewriteRulesCache
                                       .FirstOrDefault(x => x.SourceHostName.Equals(hostName, StringComparison.InvariantCultureIgnoreCase));

            if (rule == null)
            {
                // No matching rewrite rule was found.
                return;
            }

            // Set the target URL with the new hostname and the original path and query.
            string scheme = requestUrl.Scheme;
            string path   = requestUrl.AbsolutePath;
            string query  = requestUrl.Query;

            string targetUrl = string.Concat(scheme, "://", rule.TargetHostName, path, query);

            if (Settings.LogRewrites)
            {
                // Write an entry to the Sitecore log informing about the rewrite.
                Logging.LogInfo(string.Format("Hostname 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);
        }
コード例 #2
0
        /// <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);
                }
            }
        }