簡體   English   中英

web.config中的“非www到www”和“ https”重寫規則,而不是localhost ASP.NET MVC

[英]“non-www to www” and “https” rewrite rule in web.config but not localhost ASP.NET MVC

我的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 ,而且我似乎無法解決該問題-我嘗試了包含|否定規則和正則表達式| 但似乎無法找到正確的組合。 我是否以錯誤的方式處理此問題?

conditions塊中,可以使用屬性negate="true" 如果設置了此屬性且條件匹配,則不應用重寫規則。

IIS.netnegate屬性的描述:

可以通過使用元素的negate屬性來否定模式。 使用此屬性時,僅當當前URL與指定的模式不匹配時,才執行規則操作。

由於您使用的是MatchAny ,因此添加附加屬性將不匹配,因為無論如何至少要滿足其中一個條件。 我建議將2個特定的重寫規則與logicalGrouping="MatchAll" ,其中每個規則僅負責一種情況:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM