How to recognize if a request came from URL rewrite module

1.3k views Asked by At

Apologize if the title is not clear, basically I have a web proxy that listening on port 80 and I set up URL rewrite on IIS, (the rule on web.config as following), it does

http://example.com/api/blah/blah ->
http://example.com:8095/api/blah/blah

  <rule name="api-example" enabled="true" patternSyntax="ECMAScript" stopProcessing="true">
     <match url="^.*/api/.*$" />
     <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
     <action type="Rewrite" url="http://localhost:8095/{R:0}" appendQueryString="true" logRewrittenUrl="false" />
  </rule> 

it works fine, no problems, also works when I request localhost:8095 directly

but I'd also like to be able to recognize if a request was directly requested or it was via URL rewrite module.

My idea is, to append a query string onto the URL, when the url gets rewrited on IIS so that I can check if the query string exists then it was via URL rewrite if not, then it's a direct request

examples:

http://example.com/api/blah/blah?from=proxy -> http://example.com:8095/api/blah/blah?from=proxy

http://example.com/api/blah/blah?existing_query_string=blah&from=proxy -> http://example.com:8095/api/blah/blah?existing_query_string=blah&from=proxy

How can I achieve this? or is there any other way to do it?

Many thanks

Ming

3

There are 3 answers

0
Ming On

I eventually went to my own solution, which is add a query string when IIS does url rewrite and the Url rewrite module clever enough to append the querystring arr=1 to url doesn't matter whether or not the url has already had query string,

then I add code to check if the querystring contains arr=1 or not if has, then the request comes via url rewrites

<rule name="api-example" enabled="true" patternSyntax="ECMAScript" stopProcessing="true">
     <match url="^.*/api/.*$" />
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{QUERY_STRING}" pattern="(.*)" negate="false" />
      </conditions>
     <action type="Rewrite" url="http://localhost:8095/{R:0}?arr=1" appendQueryString="true" logRewrittenUrl="false" />
  </rule> 
1
Olaf On

You can try to access

Request.ServerVariables["HTTP_X_ORIGINAL_URL"]

and compare it to Request.Url.PathAndQuery. Alternatively,

Request.RawUrl

should also contain the original URL.

0
Jailhouse Joe On

Late to the party this answer but since IIS rewrite module still in use better late than never!

How about outputting a uniquely identifiable server variable whenever the rule is applied. Like...

<rule name="api-example" stopProcessing="true" enabled="true">
    <match ...
    <conditions ...
    <action type="Rewrite" ...
    <serverVariables>
        <set name="IIS_WasUrlRewritten" value="1" />
    </serverVariables>
</rule>

The rewritemodule should be setting this automatically btw