Search code examples
kentico

Kentico redirect based off URL


We have sales rep profile pages that need to be access by firstname.lastname. So an example URL would be www.mysite.com/mark.handy. This redirect to Find-A-Rep-Detail.aspx?SalesRepWebID=mark.handy.

We're currently are buildingout at a big complicated URL Rewrite that looks at the extension and goes from there. It works, but means we need to managing this either in IIS or the web.config across multiple servers.

I'm looking at a way to do this within kentico. I know the community site has profile pages that seem to take a user's firstname.aspx and redirect to a profile page.

The kentico solution would have to check the URL and if the extension doesn't match a list (aspx, html, js, css, asmx, etc) then redirect.

Here's the kicker. Our user data isn't in kentico. we have a .asps page that has a user control that grabs the name and returns the html.

I'm looking at the wildcard URL docs: https://docs.kentico.com/k9/configuring-kentico/configuring-page-urls/wildcard-urls

Is this possible in Kentico, or should we stick with the iis/web.config options?


Solution

  • As the Kentico wildcard URL docs state:

    If you need to allow dots in user names and use wildcard URLs with user names at the same time, move the wildcard in the Page URL to the middle of the URL, for example: /Members/{UserName}/Profile

    If this is not an option, and the "firstname.lastname" pattern must be the last part of the URL, a possible approach would be to use the RequestEvents.Begin global event to detect the "firstname.lastname" pattern, and redirect to the appropriate page.

    Assuming you are using Kentico 10:

    [assembly: RegisterModule(typeof(SalesRepRedirector))]
    public class SalesRepRedirector : Module
    {
        private static readonly Regex SalesRepRegex = new Regex(@"^\/([a-zA-Z]+\.[a-zA-Z]+)$");
        public SalesRepRedirector() : base("SalesRepRedirector") { }
    
        protected override void OnInit()
        {
            RequestEvents.Begin.Execute += Begin_Execute;
        }
    
        private static void Begin_Execute(object sender, EventArgs e)
        {
            var relativePath = RequestContext.CurrentRelativePath;
            var regexMatch = SalesRepRegex.Match(relativePath);
            if (regexMatch.Success)
                URLHelper.Redirect("~/Find-A-Rep-Detail.aspx?SalesRepWebID=" + regexMatch.Groups[1].Value);
        }
    }
    

    (Place the file in the App_Code folder, or in a separate assembly)

    Some things to note:

    • You need to tweak the regex, to ensure that the redirection does not affect request for files and pages (.aspx, .css, .js...)
    • There is some overhead involved when using this approach, as every request will be checked for the pattern