URL重写以将所有URL变体重定向到https://www.example.com

时间:2016-10-14 20:22:12

标签: regex https url-rewriting iis-7.5 windows-server-2008

我有一个网址,我已将SSL证书应用于www变种https://www.example.com。我希望此域名的所有变体都指向https://www.example.com

例如,以下域名应重定向到https://www.example.com

该网站托管在运行IIS7.5的Windows 2008服务器上,我使用URL Rewrite在web.config文件中创建了一些规​​则。但是,以下域名不会重定向:

以下是我目前的规则:

    <!-- Redirect http non www to https www -->
    <rule name="Redirect http://example.com to www" patternSyntax="Wildcard" stopProcessing="true">
      <match url="*" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="example.com" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
    </rule>

    <!-- Redirect http to https -->
    <rule name="Redirect http to https" enabled="true">
        <match url="(.*)" ignoreCase="false" />
        <conditions>
            <add input="{HTTPS}" pattern="off" />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
    </rule>

我很感激使用URL重写让这个工作有所帮助。理想情况下,我更愿意用一条规则替换上述内容。

2 个答案:

答案 0 :(得分:1)

让我们按照下面的逻辑,这是使用&#34; Regex&#34;。

匹配传入的任何网址,然后匹配以下任何条件。

  1. 如果主持人开始匹配example.com,则重定向
  2. 如果正在使用端口80而不是重定向。
  3. 这将涵盖将http重定向到https以及任何example.com重定向到www.example.com

    <rule name="Do It All" stopProcessing="true">
      <match url="(.*)" />
      <conditions logicalGrouping="MatchAny" trackAllCaptures="false">
        <add input="{HTTP_HOST}" pattern="^example\.com$" />
        <add input="{SERVER_PORT}" pattern="^80$" />
      </conditions>
      <action type="Redirect" url="https://www.example.com/{R:1}" appendQueryString="true" redirectType="Permanent" />
    </rule>
    

答案 1 :(得分:0)

最好使用两条规则,第一条将所有非https重定向到不包含stopProcessing=true的https,第二条将所有非www重定向到www,就像这样。

<rule name="HTTPS Redirect">
  <match url="(.*)" />
  <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
    <add input="{HTTPS}" pattern="^OFF$" />
  </conditions>
  <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
<rule name="Redirect to www">
  <match url="(.*)" />
  <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
    <add input="{HTTP_HOST}" pattern="^example\.com$" />
  </conditions>
  <action type="Redirect" url="https://www.example.com/{R:1}" redirectType="Permanent" />
</rule>

此外,您不需要appendQueryString=true{R:1}附加查询字符串。也不需要stopProcessing=true,尤其是如果您没有其他遵循的规则。不过,在大多数情况下,如果 do 遵循以下规则,则希望它们在URL重定向到https并重新格式化为www。后重新执行。