简体   繁体   中英

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

I have the following rewrite rule in the web.config of my ASP.NET MVC 5 project:

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

The rule redirects non-www to www and http to https (so something like http://example.com/hey will redirect to https://www.example.com/hey ) and works fine. It however also works on localhost , and I can't seem to be able to work around it — I've tried negation rules and regular expressions containing | but can't seem to be able to find the correct combinations. Am I approaching this the wrong way?

In conditions block you can use attribute negate="true" . If this attribute is set and condition is matched, then rewrite rule is not applied.

The description of negate attribute from IIS.net :

A pattern can be negated by using the negate attribute of the element. When this attribute is used, the rule action is performed only if the current URL does not match the specified pattern.

Since you are using MatchAny , adding additional attribute will not match, because at least one of the conditions will be met anyway. I recommend using 2 specific rewrite rules with logicalGrouping="MatchAll" , where each one is responsible just for single case:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM