Url Rewrite - Web.config - HTTPS and www

2019-09-10 01:35发布

I need to be able to redirect to HTTPS (currently working) AND www (if it's not in the URL already).

If the URL does NOT have the www, then it works fine. However, when the URL DOES have www, it redirects and adds an additional www, such as https://www.www.domain.com

Note that I do not want to hard code the domain, and would like to use HTTPHOST or something equivalent.

Current rewrite rules:

    <rule name="Redirect to HTTPS" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTPS}" pattern="^OFF$" />
      </conditions>
      <action type="Redirect" url="https://www.{HTTP_HOST}/{R:1}" redirectType="Permanent" />
    </rule>
    <rule name="WWW Rewrite" enabled="true">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTP_HOST}" negate="true" pattern="^www\.([.a-zA-Z0-9]+)$" />
      </conditions>
      <action type="Redirect" url="https://www.{HTTP_HOST}/{R:0}" appendQueryString="true" redirectType="Permanent" />
    </rule>

1条回答
三岁会撩人
2楼-- · 2019-09-10 02:30

Ended up with this Regex - ^((?!www).)*[a-zA-Z0-9]+$

I also had to go into IIS and change "Does not match the pattern" to "Matches the pattern"

    <rule name="Redirect to HTTPS" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTPS}" pattern="^OFF$" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
    </rule>
    <rule name="WWW Rewrite" enabled="true" stopProcessing="true">
      <match url="(.*)" />
      <conditions logicalGrouping="MatchAny">
        <add input="{HTTP_HOST}" pattern="^((?!www).)*[a-zA-Z0-9]+$" />
      </conditions>
      <action type="Redirect" url="https://www.{HTTP_HOST}/{R:0}" appendQueryString="true" redirectType="Permanent" />
    </rule>
查看更多
登录 后发表回答