【问题标题】:Comparison between two capture groups inside condition input of IIS web.config rewrite ruleIIS web.config重写规则条件输入内两个捕获组的比较
【发布时间】:2025-11-26 23:10:02
【问题描述】:

我正在尝试比较 IIS web.config 中重写 url 的条件输入内的两个捕获组。

我需要这样做,因为如果他们的语言代码 cookie 与 URL 中的语言不匹配,我不希望用户访问特定于语言的 URL(例如 /en/path)。

我尝试在我的 webconfig 中使用此规则来实现,但似乎无法这样做,因为服务器以 500.52 错误回答:

The expression "^((?!{C:2}).)*$" contains a repeat expression (one of '*', '?', '+', '{' in most contexts) that is not preceded by an expression.

它将我的 {C:2} 作为正则表达式本身的一部分,而不是原始字符串。

这是完整的规则:

<rule name="redirect-with-lang" stopProcessing="true">
      <match url="en\/|es\/|mx\/" ignoreCase="true"/>
      <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
        <add input="{HTTP_COOKIE}" pattern="langpref=\w{2}\/(\w{2});" />
        <add input="{REQUEST_URI}" pattern="^(\/es\/|\/en\/|\/mx\/).+$" />
        <add input="{C:1}" pattern="^((?!{C:2}).)*$"/>
      </conditions>
      <action type="Redirect" url="/{C:1}/{C:3}" />
    </rule>

我想知道是否可以在不借助 javascript 或 Global.asax 上的某些服务器代码的情况下以另一种方式实现这一目标。

谢谢

【问题讨论】:

  • 正则表达式模式应该只包含正则表达式,而不是您可能在重定向规则中使用的占位符。
  • @WiktorStribiżew 是的,正如我所写,模式属性似乎只接受正则表达式而不接受占位符。这就是为什么我要求在 web.config 中使用另一种方法来实现这一点。
  • 你应该解释一下模式应该匹配什么,结果必须是什么。
  • 另外,/ char 不用转义,没啥特殊的。

标签: c# regex asp.net-mvc iis web-config


【解决方案1】:

您可以使用此&lt;add input="{C:1}" pattern="^((?!\{C:2\}).)*$"/&gt; 条件代替&lt;add input="{C:1}" pattern="^((?!{C:2}).)*$"/&gt;

您收到此错误是因为大括号 - { } 在条件中。

【讨论】:

    最近更新 更多