Search code examples
asp.net-mvcazureweb-confighttp-redirect

301 redirect in Azure ASP.Net Core website


Google is getting confused about which page to index, even though it is all nicely explained in the sitemap.

I created a redirect rule in web.config to redirect traffic from naked to www and this works great

 <rule name="Redirect to www" patternSyntax="Wildcard" stopProcessing="true">
        <match url="*" />
        <conditions>
          <add input="{HTTP_HOST}" pattern="example.com" />
        </conditions>
        <action type="Redirect" url="https://www.example.com/{R:0}" redirectType="Permanent" />
      </rule>

I am trying to create a second rule to redirect domain/home/index and domain/index to root but am not able to. Below doesn't work. I tried a few variations with different regex in pattern fields, but nothing is working.

    <rule name="Redirect index" patternSyntax="Wildcard" stopProcessing="true">
      <match url="*" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="example.com/home/index" />
      </conditions>
      <action type="Redirect" url="https://www.example.com/" redirectType="Permanent" />
    </rule>

Solution

  • This did the trick. This converts URL to lowercase, redirects domain/home/index and domain/home to domain and domain/home/something to domain/something. Also adds www to naked domain.

    Perhaps this should be a default behaviour?

    Please let me know if there's a better way

    <rewrite>
      <rules>
        <rule name="Convert to lower case" stopProcessing="false">
          <match url=".*[A-Z].*" ignoreCase="false" />
          <action type="Redirect" url="{ToLower:{R:0}}" redirectType="Permanent" />
        </rule>
        <rule name="Redirect index" patternSyntax="Wildcard" stopProcessing="true">
          <match url="home/index" />
          <action type="Redirect" url="https://www.example.com" redirectType="Permanent" />
        </rule>
        <rule name="Redirect home" patternSyntax="Wildcard" stopProcessing="true">
          <match url="home" />
          <action type="Redirect" url="https://www.example.com" redirectType="Permanent" />
        </rule>
        <rule name="Redirect home2" patternSyntax="Wildcard" stopProcessing="true">
          <match url="home/*" />
          <action type="Redirect" url="https://www.example.com/{R:1}" redirectType="Permanent" />
        </rule>
        <rule name="Redirect to www" patternSyntax="Wildcard" stopProcessing="true">
          <match url="*" />
          <conditions>
            <add input="{HTTP_HOST}" pattern="^example.com" />
          </conditions>
          <action type="Redirect" url="https://www.example.com/{R:0}" redirectType="Permanent" />
        </rule>
      </rules>