正则表达式匹配除特定路径之外的所有https URL

时间:2013-08-05 20:33:27

标签: regex iis url-rewriting

我需要一个匹配除特定路径之外的所有https网址的正则表达式。

e.g。

匹配

https://www.domain.com/blog https://www.domain.com

不匹配

https://www.domain.com/forms/ *

这是我到目前为止所做的:

<rule name="Redirect from HTTPS to HTTP excluding /forms" enabled="true" stopProcessing="true">
    <match url=".*" />
    <conditions>
        <add input="{URL}" pattern="^https://[^/]+(/(?!(forms/|forms$)).*)?$" />
    </conditions>
    <action type="Redirect" url="http://{HTTP_HOST}/{R:0}" redirectType="Permanent" />
</rule>

但它不起作用

4 个答案:

答案 0 :(得分:5)

重定向模块的工作方式,您只需使用:

<rule name="Redirect from HTTPS to HTTP excluding /forms" stopProcessing="true">
    <match url="^forms/?" negate="true" />
    <conditions>
        <add input="{HTTPS}" pattern="^ON$" />
    </conditions>
    <action type="Redirect" url="http://{HTTP_HOST}/{R:0}" />
</rule>

仅当请求为HTTPS并且路径未以forms/forms(使用negate="true"选项)开头时,规则才会触发重定向到HTTP。 /> 您还可以为主机添加条件以匹配www.example.com,如下所示:

<rule name="Redirect from HTTPS to HTTP excluding /forms" stopProcessing="true">
    <match url="^forms/?" negate="true" />
    <conditions>
        <add input="{HTTPS}" pattern="^ON$" />
        <add input="{HTTP_HOST}" pattern="^www.example.com$" />
    </conditions>
    <action type="Redirect" url="http://{HTTP_HOST}/{R:0}" />
</rule>

答案 1 :(得分:4)

我想出了以下模式:^https://[^/]+(/(?!form/|form$).*)?$

<强>解释

  • ^:匹配字符串的开头
  • https://:匹配https://
  • [^/]+:匹配除正斜杠之外的任何内容一次或多次
  • (:开始匹配第1组
    • /:匹配/
    • (?!:负向前瞻
      • form/:检查是否没有form/
      • |:或
      • form$:检查字符串末尾是否有form
    • ):end negative lookahead
    • .*:匹配所有内容零次或多次
  • ):结束匹配组1
  • ?:将上一个令牌设为可选
  • $:匹配行尾

答案 2 :(得分:4)

这会为您提供您正在寻找的行为吗?

https?://[^/]+($|/(?!forms)/?.*$)

www.domain.com位之后,它正在寻找字符串的结尾,或者斜杠,然后是非forms的东西。

答案 3 :(得分:3)

我在发布的模式http://[^/]+($|/(?!forms)/?.*$)

中看到了两个问题
  • 它错过了重定向https://domain.com/forms_instructions等网址,因为该模式也无法匹配。

  • 我相信你在模式和网址之间反转了http和https。该模式应具有https和网址http

也许这会按你的意思运作:

 <rule name="Redirect from HTTPS to HTTP excluding /forms" enabled="true" stopProcessing="true">
        <match url="^https://[^/]+(/(?!(forms/|forms$)).*)?$" />
        <action type="Redirect" url="http://{HTTP_HOST}{R:1}" redirectType="Permanent" />
    </rule>

编辑:我已经将模式移动到标签本身,因为将所有内容与。*匹配,然后使用附加条件似乎是不必要的。我还更改了重定向URL,以使用匹配中括号捕获的输入URL部分。

相关问题