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

Fix the URL Rewrite error "Rewrite error: Expression contains a repeat expression" on Windows Server IIS.

How to fix the HTTP Error 500.52 – URL Rewrite Module Error. error in URL Rewrite

The other day, I had to migrate a website from a Linux/Apache web server to Windows Server IIS. The website in question has a lot of sub domains, all pointing to folders within the web root using that same name: foobar.example.com would go to www.example.com/foobar.

For this to happen we usually use an URL Rewrite 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 produces an error:

HTTP Error 500.52 - URL Rewrite Module Error.
The expression "^/{C:1}" contains a repeat expression (one of '*', '?', '+', '{' in most contexts) that is not preceded by an expression.

Fixing the URL Rewrite error by escaping accolade chars

You can fix this URL Rewrite error by escaping the accolade characters { } in the second input condition:

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

The 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 we’re not rewriting www.example.com to www.example.com/www, exclude that sub domain first:

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

Posted by Jan Reilink

My name is Jan. I am not a hacker, coder, developer, programmer or guru. I am merely a system administrator, doing my daily thing at Vevida in the Netherlands. With over 15 years of experience, my specialties include Windows Server, IIS, Linux (CentOS, Debian), security, PHP, websites & optimization. Want to support me and donate? Use this link: https://paypal.me/jreilink.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.