如何在 web.config 中将非 WWW 重定向到 WWW

How to redirect non WWW to WWW in web.config

我在这里试过web.config redirect non-www to www

并尝试过:

<rule name="ensurewww" enabled="false" stopProcessing="true">
    <match url=".*" />
    <conditions>
         <add input="{CACHE_URL}" pattern="^(.+)://(?!www)(.*)" />
    </conditions>
    <action type="Redirect" url="{C:1}://www.{C:2}/{R:1}" redirectType="Permanent" />
</rule>

Result: 1. abc.com ---> www.abc.com True

Result 2. abc.com/a.aspx--->www.abc.com/a.aspx False

Result 3. abc/com/abc---->www.abc.com/abc False

Finally: I want to Result 2 and Result 3 is True

尝试过:

<rule name="Force WWW and SSL" enabled="true" stopProcessing="true">
      <match url="(.*)" />
      <conditions logicalGrouping="MatchAny">
          <add input="{HTTP_HOST}" pattern="^[^www]" />
          <add input="{HTTPS}" pattern="off" />
      </conditions>
      <action type="Redirect" url="https://www.obu.vn/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>

It will Redirect non www to www and http to https

这是我的通用版本。请注意,这也会将任何 http 重定向到 https 版本。例如:

http://test.com  → https://www.test.com
https://test.com → https://www.test.com

另请注意,我为 //localhost 添加了一个例外。这是因为我将此代码用于我的 asp.net Web 应用程序,并且我不想在开发时将 http://localhost 重定向到 http://www.localhost ...

<rule name="RedirectNonWwwToHttpsWww" stopProcessing="true">
  <match url=".*" />
  <conditions>
    <add input="{HTTP_HOST}" pattern="^www\." negate="true" />
    <add input="{HTTP_HOST}" pattern="^localhost" negate="true" />
  </conditions>
  <action type="Redirect" url="https://www.{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
</rule>