I need to write a URL Rewrite rule for my IIS 7.5 website that captures a value in a particular cookie, and then uses that value to construct a URL. For instance, the incoming requests looks like this:
GET http://myserver.com/test.aspx HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: en-US
User-Agent: Mozilla/5.0
Host: myserver.com
Cookie: foo=bar; bat=bar
I'd like to route them to this (based on the "foo" cookie value):
http://myserver.com/bar/test.aspx
fter reviewing the documentation and searching for examples, I'm stumped! Thanks for your help.
The URL rewriting module runs early in the request-processing pipeline, modifying the requested URL before the Web server decides which handler to use to process the request. The handler, which is chosen based on the rewritten URL, processes the request and generates a response that is sent back to the Web browser.
The URL Rewrite Module enables web administrators to develop and implement rules that assist them in this task. URLs generated by web applications may not necessarily be user-friendly. The URL Rewrite Module will replace these with the friendlier version of the URL. It can be used to implement complex rewrite logic.
Answering my own question, here's a working example. The pattern may need additional work depending on what characters require supporting, but the following rule will will use the discovered cookie value and route to the discovered server--and the server can be specified by IPv4 address or by name (alphanumeric-and-period).
<rule name="Route Base On Cookie" stopProcessing="true">
<match url="^(.*)" />
<conditions>
<add input="{HTTP_COOKIE}" pattern="foo=(.*?);" />
</conditions>
<action type="Rewrite" url="http://{C:1}/{R:0}" />
</rule>
@Geoffrey To make your code support returning any cookie value, I'd recommend this pattern:
<add input="{HTTP_COOKIE}" pattern="foo=(.*?);" />
As a reminder, the {HTTP_COOKIE} value looks like this for example:
Cookie: foo=myexamplevalue; expires=Wed, 03-May-2014 22:31:08 GMT; path=/; HttpOnly\r\n
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With