From af062229f96962bd46212b5844dc802029d0620c Mon Sep 17 00:00:00 2001 From: nathans Date: Fri, 10 Aug 2018 15:50:29 +0100 Subject: [PATCH] Added Regex group matching to allow relative URL redirection - e.g. /page-old/child-pages (many) to be directed to /page-new/child-pages (many) in one redirect entry --- .../Simple301/Core/RedirectContentFinder.cs | 27 ++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/source/Simple301/Core/RedirectContentFinder.cs b/source/Simple301/Core/RedirectContentFinder.cs index ba95048..92c61e5 100644 --- a/source/Simple301/Core/RedirectContentFinder.cs +++ b/source/Simple301/Core/RedirectContentFinder.cs @@ -1,5 +1,6 @@ -using Umbraco.Web.Routing; -using System.Linq; +using System; +using System.Text.RegularExpressions; +using Umbraco.Web.Routing; namespace Simple301.Core { @@ -18,8 +19,28 @@ public bool TryFindContent(PublishedContentRequest request) var matchedRedirect = RedirectRepository.FindRedirect(path); if (matchedRedirect == null) return false; + // Groups match replace + string newUrl = matchedRedirect.NewUrl; + + if (matchedRedirect.IsRegex && matchedRedirect.OldUrl.Contains("(.*)")) + { + try + { + var match = Regex.Match(path, matchedRedirect.OldUrl); + + for (int iGrp = 1; iGrp < match.Groups.Count; iGrp++) + { + newUrl = newUrl.Replace($"${iGrp}", match.Groups[iGrp].Value); + } + } + catch (Exception) + { + return false; + } + } + //Found one, set the 301 redirect on the request and return - request.SetRedirectPermanent(matchedRedirect.NewUrl); + request.SetRedirectPermanent(newUrl); return true; } }