如何识别请求是否来自URL重写模块

问题描述 投票:0回答:3

如果标题不清楚,请原谅,基本上我有一个监听端口 80 的 Web 代理,并且我在 IIS 上设置了 URL 重写,(web.config 上的规则如下),确实如此

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> 

它工作正常,没有问题,当我直接请求 localhost:8095 时也可以工作

但我也希望能够识别请求是直接请求的还是通过 URL 重写模块发出的。

我的想法是,在URL上附加一个查询字符串,当URL在IIS上被重写时,我可以检查查询字符串是否存在,然后通过URL重写,如果不存在,那么它是一个直接请求

示例:

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

我怎样才能实现这个目标?或者还有其他办法吗?

非常感谢

c# iis url-rewriting arr
3个回答
1
投票

我最终采用了自己的解决方案,即在 IIS 进行 url 重写时添加查询字符串 并且 Url 重写模块足够聪明,可以将查询字符串 arr=1 附加到 url 中,无论 url 是否已经有查询字符串,

然后我添加代码来检查查询字符串是否包含 arr=1 如果有,则请求通过 url 重写来

<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> 

0
投票

您可以尝试访问

Request.ServerVariables["HTTP_X_ORIGINAL_URL"]

并将其与 Request.Url.PathAndQuery 进行比较。或者,

Request.RawUrl

还应包含原始 URL。


0
投票

这个答案迟到了,但由于 IIS 重写模块仍在使用,迟到总比不到好!

如何在应用规则时输出唯一可识别的服务器变量。就像...

<rule name="api-example" stopProcessing="true" enabled="true">
    <match ...
    <conditions ...
    <action ...
    <serverVariables>
        <set name="IIS_WasUrlRewritten" value="true" />
    </serverVariables>
</rule>
© www.soinside.com 2019 - 2024. All rights reserved.