【问题标题】:"non-www to www" and "https" rewrite rule in web.config but not localhost ASP.NET MVCweb.config 中的“非 www 到 www”和“https”重写规则,但不是 localhost ASP.NET MVC
【发布时间】:2023-03-14 15:40:02
【问题描述】:

我的 ASP.NET MVC 5 项目的web.config 中有以下重写规则:

<rule name="Redirect example.com to www.example.com and enforce https" enabled="true" stopProcessing="true">
    <match url="(.*)" />
    <conditions logicalGrouping="MatchAny">
        <add input="{HTTP_HOST}" pattern="^[^www]" />
        <add input="{HTTPS}" pattern="off" />
    </conditions>
    <action type="Redirect" url="https://www.example.com/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>

该规则将非 www 重定向到 www 并将 http 重定向到 https(因此 http://example.com/hey 之类的东西将重定向到 https://www.example.com/hey)并且工作正常。然而,它也适用于localhost,我似乎无法解决它——我尝试了包含| 的否定规则和正则表达式,但似乎无法找到正确的组合。我是不是走错了路?

【问题讨论】:

    标签: asp.net asp.net-mvc iis url-rewriting web-config


    【解决方案1】:

    conditions 块中,您可以使用属性negate="true"。如果设置了该属性且条件匹配,则不应用重写规则。

    negate属性的描述来自IIS.net

    一个模式可以通过使用 negate 属性来否定 元素。使用该属性时,执行规则动作 仅当当前 URL 与指定的模式不匹配时。

    由于您使用的是MatchAny,因此添加附加属性将不匹配,因为无论如何至少会满足其中一个条件。我建议使用 logicalGrouping="MatchAll" 的 2 条特定重写规则,其中每条规则只负责单个案例:

    <rule name="enforce https" enabled="true" stopProcessing="true">
        <match url="(.*)" />
        <conditions logicalGrouping="MatchAll">
            <add input="{HTTPS}" pattern="off" />
            <add input="{HTTP_HOST}" matchType="Pattern" 
                  pattern="^localhost(:\d+)?$" negate="true" />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"
              appendQueryString="true" redirectType="Permanent" />
    </rule>
    <rule name="Redirect example.com to www.example.com"
           enabled="true" stopProcessing="true">
        <match url="(.*)" />
        <conditions logicalGrouping="MatchAll">
            <add input="{HTTP_HOST}" pattern="^[^www]" />
            <add input="{HTTP_HOST}" matchType="Pattern" 
                  pattern="^localhost(:\d+)?$" negate="true" />
        </conditions>
        <action type="Redirect" url="https://www.example.com/{R:1}"
             appendQueryString="true" redirectType="Permanent" />
    </rule>     
    

    【讨论】:

    • 谢谢,我在实时网站上的 Chrome 中得到了这个:“www.example.com 将您重定向了太多次。ERR_TOO_MANY_REDIRECTS” - 在 Firefox 中也是如此
    • @globetrotter 我认为这是MatchAny 的问题 - 看看MatchAll 的更新答案是否有帮助
    • 现在它适用于实时站点,但尝试在 localhost 上添加 https
    • 你在 localhost 上使用 80 以外的端口吗?
    • @globetrotter 我更新了答案以支持本地主机上的端口
    猜你喜欢
    • 2017-12-04
    • 1970-01-01
    • 2020-11-28
    • 2014-12-16
    • 1970-01-01
    • 2020-10-05
    • 2019-02-04
    • 1970-01-01
    • 2015-06-18
    相关资源
    最近更新 更多