IIS URL Rewrite Module in IIS Manager

IIS URL Rewrite Module “Rewrite Module error: Expression contains a repeat expression”

Fix for IIS URL Rewrite Module error "Rewrite Module error: Expression contains a repeat expression"

Home » Windows Server » IIS URL Rewrite Module “Rewrite Module error: Expression contains a repeat expression”

The other day, I had to migrate a website from a Linux / Apache web server to Windows Server IIS. Yes, that type of migration happens too, sometimes. The website in question had a lot of sub domains, all pointing to folders within the web root using that same name: foobar.example.com would redirect (rewrite) to www.example.com/foobar.

For this to happen we usually use an IIS URL Rewrite Module rule for one sub domain in a web.config file:

<rules>
  <rule name="Own website for sub domain">
    <match url="(.*)" />
    <conditions trackAllCaptures="true">
      <add input="{HTTP_HOST}" pattern="^(foobar)\.example\.com$" />
      <add input="{PATH_INFO}" pattern="^/foobar" negate="true" />
    </conditions>
    <action type="Rewrite" url="/{C:1}/{R:1}" />
  </rule>

However, this would mean I had to add and use that same rule some fifty times… Not good!

I simplified the rewrites by using the value of the first condition (HTTP_HOST, or foobar) as input for the second condition PATH_INFO. Now logically you want to substitute ^/foobar with ^/{C:1}, to use the value of the first condition as input for the second condition in your rewrite rule:

<add input="{PATH_INFO}" pattern="^/{C:1}" negate="true" />

This produced an IIS URL Rewrite Module error:

HTTP Error 500.52 – URL Rewrite Module Error.
The expression “^/” contains a repeat expression (one of ‘*’, ‘?’, ‘+’, ‘{‘ in most contexts) that is not preceded by an expression.

Fixing the IIS URL Rewrite Module error by escaping braces

After some investigation and testing, I found you can fix this IIS URL Rewrite Module error by escaping braces – { } – in the second input condition:

<add input="{PATH_INFO}" pattern="^/\{C:1\}" negate="true" />

The complete rewrite becomes:

<rules>
  <rule name="Own website for sub domain">
    <match url="(.*)" />
    <conditions trackAllCaptures="true">
      <add input="{HTTP_HOST}" pattern="^(foobar)\.example\.com$" />
      <add input="{PATH_INFO}" pattern="^/\{C:1\}" negate="true" />
    </conditions>
    <action type="Rewrite" url="/{C:1}/{R:1}" />
  </rule>

To make sure you’re not rewriting www.example.com to www.example.com/www, exclude that sub domain first by using negate:

<add input="{HTTP_HOST}" pattern="^www" negate="true" />
Jan Reilink
Jan Reilink

In my day to day work, I’m a systems administrator – DevOps / SRE and applications manager at Embrace – The Human Cloud. At Embrace we develop, maintain and host social intranets for our clients. Provide digital services and make working more efficient within various sectors.

Read why we can use your help and support ❤️

Articles: 173