CB Du Rietz
CB Du Rietz

Reputation: 197

Using URL Rewrite to change part of URL

I'm trying to use an URL Rewrite on an IIS 8.0 to rewrite existing URL:s on a developer machine. The reason for this is that I don't want to change existing (old) code.

What I'm trying to achieve is to change the following code in the response stream:

<a href="http://www.foo.com/path/page.asp?a=1">Foo Page</a>

into:

<a href="http://www.foo.localhost/path/page.asp?a=1">Foo Page</a>

But when I'm trying, I end up with:

<a href="foo.localhost">Foo Page</a>

And as you all know, this is not a very satisfying result.

So - how do I do this rewrite proper to achieve what I'm trying to do?

I know there are better ways of doing this, using application variables etc., but it's an old solution and I don't want to mess too much with the application itself. I want to keep the changes to a minimum. At least to begin with.

The rules I tried look like this:

<system.webServer>
  <rewrite>
    <outboundRules>
      <rule name="foo.com" enabled="true">
        <match filterByTags="A, Area, Base, Form, Frame, Head, IFrame, Img, Input, Link, Script" pattern="foo.com" />
        <action type="Rewrite" value="foo.localhost" />
      </rule>
    </outboundRules>
  </rewrite>
</system.webServer>

I guess there is some regex magic I should be using.

Upvotes: 5

Views: 9342

Answers (1)

cheesemacfly
cheesemacfly

Reputation: 11762

Your rule needs to be changed to:

<rule name="foo.com" enabled="true">
  <match filterByTags="A, Area, Base, Form, Frame, Head, IFrame, Img, Input, Link, Script" pattern="^(.*)foo.com(.*)$" />
  <action type="Rewrite" value="{R:1}foo.localhost{R:2}" />
</rule>

In the pattern, ^(.*) will match anything (0 or more characters) from the beginning before foo.com and (.*)$ anything after foo.com until the end.

You can then use the back references in the action, where {R:1} will take the value matching (.*) before foo.com and {R:2} the value matching (.*) after foo.com

Upvotes: 6

Related Questions