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.mydomain.com then it will go to https://www.mydomain.com.
I want ALL traffic to go to https://www.mydomain.com. Is this possible using the rules element of the web.config? My file currently looks like this:
<rewrite>
<rules>
<rule name="HTTP to HTTPS redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
</rule>
</rules>
<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>
<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.
{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}".
<action redirectType>
can be Temporary, Found or SeeOther. (See here for more info.)
<conditions logicalGrouping>
can be MatchAll or MatchAny.
For a more complete explanation please see here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With