简体   繁体   English

Web.config 将 www 和非 www 重定向到 https

[英]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. 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.它似乎只喜欢 www 选项,因为它在 www 和非 www 或非 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.首先,为了排除浏览器缓存的影响,我们应该始终在浏览器隐身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. Google Chrome默认禁用Http协议,请注意查看浏览器地址栏中实际的URL。
If we just want to redirect the Http to https, it is enough to add the {HTTPS} server variable to match Non-http protocol.如果我们只想将 Http 重定向到 https,添加{HTTPS}服务器变量以匹配Non-http协议就足够了。

        <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.为了强制使用WWW前缀,请参考以下规则。 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.如果问题仍然存在,请随时告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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