使用IIS7 URL重写模块强制HTTPS并避免重复的URL

问题描述:

我需要强制每个请求 https://www.mysite.com (始终使用https和www )

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

该网站托管在GoDaddy中,我需要通过IIS7 URL重写模块进行。

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

I已经能够使用以下代码进行HTTPS重定向:

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>

测试用例

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

我想在浏览器中输入www.mysite.com时,条件不满意,所以没有重定向该页面用作HTTP而不是HTTPS。

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.

我想我只需要修改条件模式,但我几乎没有正则表达式知识,我需要这个asap。

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

谢谢!

emzero,我认为问题在于你的问题条件仅精确匹配 mysite.com

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

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

注意模式: ^ mysite\.com $ 。这用英语说,传入的URL必须以 mysite.com 开头,以 mysite.com 结尾,这意味着 www.mysite.com 匹配。

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.

请尝试使用此模式,允许选项 www。

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

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

快乐编程!