Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing a Value in a Cookie using URL Rewrite for IIS7

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.

like image 518
Geoffrey McGrath Avatar asked Jan 06 '12 20:01

Geoffrey McGrath


People also ask

How does IIS URL Rewrite work?

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.

Is URL Rewrite module?

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.


2 Answers

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>
like image 159
Geoffrey McGrath Avatar answered Oct 02 '22 12:10

Geoffrey McGrath


@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

like image 24
Kevin Avatar answered Oct 02 '22 14:10

Kevin