Forcing HTTPS and avoid duplicate URLS using IIS7

2019-04-12 13:12发布

问题:

I need to force every request to https://www.mysite.com (always with https and www)

The site is hosted in GoDaddy and I need to do it via IIS7 URL Rewrite Module.

I've been able to do the HTTPS redirect with the following code:

<system.webServer>
        <rewrite>
            <rules>
                <rule name="Canonical Host Name" stopProcessing="true">
                    <match url="(.*)" />

                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^mysite\.com$" />
                    </conditions>

                    <action type="Redirect" url="https://www.mysite.com/{R:1}" redirectType="Permanent" />
                </rule>
            </rules>
        </rewrite>
</system.webServer>

Test cases

  • http://mysite.com -> https://www.mysite.com OK
  • http://www.mysite.com -> https://www.mysite.com NOT WORKING

I guess the condition is not being satisfied when I enter www.mysite.com in the browser, so there's no redirect and the page serves as HTTP instead of HTTPS.

I think I just need to modify the condition pattern, but I have almost nothing regex knowledge and I need this asap.

Thanks!

回答1:

emzero, I think the issue is that your condition only matches precisely mysite.com:

<conditions>
    <add input="{HTTP_HOST}" pattern="^mysite\.com$" />
</conditions>

Note the pattern: ^mysite\.com$. This says, in English, that the incoming URL must start with mysite.com and end with mysite.com, meaning www.mysite.com will not be matched.

Try this pattern instead, which allows for an option www.:

<conditions>
    <add input="{HTTP_HOST}" pattern="^(www\.)?mysite\.com$" />
</conditions>

Happy Programming!