Search code examples
asp.netasp.net-coreiisasp.net-web-apiweb-config

Redirect from www to none-www not working


The app is built on asp.net core 3.1 and react. They are on the same origin.

In web.config redirection from http to https working.

In web.config redirection from www.example.com to example.com not working

        // Piece of my web.config
        <rules>
          <rule name="HTTP to HTTPS redirect" stopProcessing="true">
            <match url="(.*)" />
            <conditions>
              <add input="{HTTPS}" pattern="off" ignoreCase="true" />
            </conditions>
            <action type="Redirect" redirectType="Permanent" url="https://{HTTP_HOST}/{R:1}" />
          </rule>
          <rule name="RedirectWwwToNonWww" stopProcessing="false">
            <match url="(.*)" />
            <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
              <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
            </conditions>
            <action type="Redirect" url="https://{C:2}{REQUEST_URI}" redirectType="Permanent" />
          </rule>
        </rules>

  • In browser www.example.com goes in redirection loop and shows ERR_TOO_MANY_REDIRECTS
  • In Postman the error is Error: Exceeded maxRedirects. Probably stuck in a redirect loop https://www.example.com/

Solution

  • You can try this rule to redirect from www to none-www:

    <rule name="SecureRedirect" stopProcessing="true">
      <match url="^(.*)$" />
        <conditions>
          <add input="{HTTPS}" pattern="off" />
          <add input="{HTTP_HOST}" pattern="^(www\.)?(.*)$" />
        </conditions>
      <action type="Redirect" url="https://{C:2}" redirectType="Permanent" />
    </rule>