简体   繁体   中英

Web.config redirect of both www and non-www to https

I had success redirecting www.example.com to https://example.com but not both www.example.com and example.com. Here's my code to redirect both:

 <rewrite> <rules> <rule name="Force www and non-www" stopProcessing="true"> <match url="(.*)" /> <conditions logicalGrouping="MatchAny" trackAllCaptures="false"> <add input="{HTTP_HOST}{REQUEST_URI}" pattern="www.example.com" /> <add input="{HTTP_HOST}{REQUEST_URI}" pattern="example.com" /> </conditions> <action type="Redirect" url="https://example.com/{R:1}" redirectType="Permanent"/> </rule> </rules> </rewrite>

It only seems to like the www option because it fails with either both www and non-www or just with non-www. Is there something wrong with the code?

At first, for excluding the impact of the browser's cache, we should always test it in the browser incognito window. In addition, please restart the server to apply the latest changes. Google Chrome disable the Http protocol by default, please pay attention to check the actual URL in the browser address bar.
If we just want to redirect the Http to https, it is enough to add the {HTTPS} server variable to match Non-http protocol.

        <rules>
    <rule name="Force WWW and SSL" enabled="true" stopProcessing="true">
      <match url="(.*)" />
      <conditions logicalGrouping="MatchAll">
                    <add input="{HTTPS}" pattern="off" />
                    <add input="{HTTP_HOST" pattern="example.com|www.example.com" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="true" redirectType="Permanent" />
    </rule>
  </rules>

In order to forcibly use the WWW prefix, please refer to the below rule. Please pay attention to pattern mode.

   <rule name="Force www" enabled="true" stopProcessing="false">
        <match url="(.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
            <add input="{HTTP_HOST}" pattern="^example\.com$" />
        </conditions>
        <action type="Redirect" url="https://www.example.com{REQUEST_URI}" />
    </rule>

Feel free to let me know if the problem still exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM