'IIS Rewrite - redirect site to new domain capturing the language embedded in the URL

I am trying to write a regex to redirect the URL to a new domain. I wrote IIS Rewrite rule for this:

<rule name="Redirect to new domain" stopProcessing="true">
          <match url="^(.*)" />
          <conditions>
            <add input="{HTTP_HOST}" pattern="^(www\.)?my-www-en\.sites\.company\.net(\/([a-zA-Z]{2,3}-[a-zA-Z]{2,3}|en)\/?)?(.*$)" />
          </conditions>
          <action type="Redirect" redirectType="Permanent" url="https://my-new-domain.com/en-us/{C:4}" appendQueryString="true" />
</rule>

It works fine when the language is not added to the initial URL, however, some of the pages have the language added after the domain which results in double language appearance in the end URL. So basically I would like to redirect things like:

my-www-en.sites.company.net/some-page/another/page/
www.my-www-en.sites.company.net/some-page/another/page/
my-www-en.sites.company.net/de-de/some-page/another/page/
www.my-www-en.sites.company.net/de-de/some-page/another/page/
my-www-en.sites.company.net/en/some-page/another/page/

to redirect to:

https://my-new-domain.com/en-us/some-page/another/page/

My current regex does not capture these groups correctly (even when it does while testing the regex in IIS rewrite) and I struggle to make it work. Right now everything gets redirected to the homepage instead to particular websites. Could you please help?



Solution 1:[1]

Please try this rule. The regular expressions can match all urls above.

<rule name="test">
                <match url=".*" />
                <conditions>
                    <add input="{HTTP_HOST}" pattern="^(www\.)?my-www-en\.sites\.company\.net$" />
                    <add input="{REQUEST_URI}" pattern="(/.*)?(/some-page/another/page/)" />
                </conditions>
                <action type="Rewrite" url="https://my-new-domain.com/en-us{C:2}" />

You can change rewrite to redirect.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bruce Zhang