1

My regex skills are limited but I have managed to come up with an expression which seems to match what I want but the problem I have is using the matched part of my expression.

Rule is as follows:

<rule name="FixDestinationCategories" stopProcessing="false">
    <match url="^([^\/]+\/){2,4}category/([^\/]+\/){2}/?$" />
    <action type="Redirect" appendQueryString="true" redirectType="Permanent" url="{R:1}" />
</rule>

An example urls might be as follows:

country/destinations/itineraries/itinerary/category/region/country/
another/directory/category/region/country/

Due to an issue on the site, I am trying to 301 redirect links on the site to remove the last 3 segments of the url. The number of segments before that can vary between 2 and 4. What I want to do is grab the entire path before /category/region/country/, I also need to ensure that the resulting path ends with a trailing slash so the redirects in the above examples would end up being:

country/destinations/itineraries/itinerary/
another/directory/

However, as it is at the moment my redirect urls ends up being:

itinerary/
directory/

I've done a lot of searching for a solution but in this case I'm not sure I even know the terminology to use for my search as most of what I've read on backreferences seem to deal with single matches.

ProNotion
  • 3,662
  • 3
  • 21
  • 30

1 Answers1

1

You need to make the first and second capturing groups non-capturing and wrap the first group with its quantifier with a capturing one:

^((?:[^/]+/){2,4})category/(?:[^/]+/){2}/?$
 ^^^^            ^          ^^

See the regex demo

The ((?:[^/]+/){2,4}) is a capturing group with ID 1 that matches 2, 3 or 4 consecutive occurrences of 1+ chars other than / and then a /. The ?: after ( form a non-capturing group that is only used to group a sequence of patterns, but does not store a submatch in memory and the contents cannot be referenced after a match is found.

Those green-highlighted parts are the substrings captured into Group 1, the {R:1} placeholder refers to:

enter image description here

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Thanks so much, that works perfectly and thank you also for the explanation, that will prove invaluable for future reference! – ProNotion Jun 28 '18 at 13:17