Web.config. Redirect all traffic to www.my… Using rules element.

前端 未结 1 948
花落未央
花落未央 2021-02-05 15:22

I have a web.config file which automatically sends traffic to HTTPS. However, if someone enters in MyDomain.com then it will go to https://mydomain.com and if someone enters www

相关标签:
1条回答
  • 2021-02-05 16:17

    The Rule

    <rule name="Redirect to www subdomain">
    
      <match url=".*" />
    
      <conditions logicalGrouping="MatchAll">
        <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" negate="true" />
        <add input="{SERVER_PROTOCOL}" pattern="^(.*)(/.*)?$"/>
      </conditions>
    
      <action type="Redirect" url="{C:1}://www.{HTTP_HOST}/{R:0}" redirectType="Permanent"/>
    
    </rule>
    

    Explanation of Rule

    • <match /> Limits a rule to only requests whose path and query string match the given pattern. In our case we want to match all paths and query strings since we will redirect based on domain.

    • <conditions /> Limits a rule even further to just the matched requests that satisfy the given conditions. The first condition excludes requests whose domain already starts with "www". The second condition is there just for the {C:1} backreference and it shouldn't filter out anything.

    • <action> prepends "www." to the domain and then redirects.

    Variables

    • {R:0} is a backreference to the full match from the <match \> tag. The back-reference should only contain the path and query string since that is all that <match \> ever matches against.

    • {C:1} is a backreference to the first match group from the final condition. This should contain everything up to the "/" in the {SERVER_PROTOCOL} variable.

    • {HTTP_HOST} is a server variable that contains the requested domain. (See here for a full list.)

    • {SERVER_PROTOCOL} another server variable. Its format should be "{protocol}/{version number}".

    Other Options

    • <action redirectType> can be Temporary, Found or SeeOther. (See here for more info.)

    • <conditions logicalGrouping> can be MatchAll or MatchAny.

    Conclusion

    For a more complete explanation please see here.

    0 讨论(0)
提交回复
热议问题