Search code examples
http-redirectiisweb-configiis-10

Trouble getting redirects right using web.config for IIS


Ok have a strange redirect issue here. I have 3 domain names so lets call them the following

maindomain.com
aliasdomain.net
aliasdomain.org

We are using Let's Encrypt for https via IIS on a windows 2016 Server.

What we want is for anytime a person types in any of the 3 domains with or the www to all redirect to the domain name www.maindomain.com

Since the let's encrypt certificate is not creating www. versions for the domain aliases it is causing us some struggles. This is the web.config rules we are using but they do not work.

<rule name="Redirect to WWW" enabled="true">
    <match url="(.*)" />
    <conditions>
        <add input="{HTTP_HOST}" pattern="^www\." negate="true" />
    </conditions>
    <action type="Redirect" url="https://www.{HTTP_HOST}{HTTP_URL}" redirectType="Permanent" appendQueryString="false" />
</rule>
<rule name="Redirect to HTTPS" enabled="true">
    <match url="(.*)" />
    <conditions>
        <add input="{HTTPS}" pattern="OFF" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}{HTTP_URL}" redirectType="Permanent" appendQueryString="false" />
</rule>

So the results of this are the following This works www.maindomain.com works and redirects to https://www.maindomain.com maindomain.com works and redirects to https://www.maindomain.com

This doesn't work and oddly enough shows the standard IIS landing page aliasdomain.net doesn't work redirects to http://www.aliasdomain.net www.aliasdomain.net doesn't work and redirects to http://www.aliasdomain.net

This one doesn't work at all aliasdomain.org doesn't work redirects to https://www.aliasdomain.org www.aliasdomain.org doesn't work and redirects to https://www.aliasdomain.org

No idea how to get this to do what we want. You would think it would not be some difficult to redirect any version of any domain name to the https://www.maindomain.com

Thanks for any help here.


Solution

  • The problem with your rule is that you are using {HTTP_HOST} in your redirect action.This parameter will take the incoming hostname from the request.I think that is not what you want. <action type="Redirect" url="https://{HTTP_HOST}{HTTP_URL}" redirectType="Permanent" appendQueryString="false" />

    Please try below rule. It redirects if the hostname does not match www.maindomain.com ,also enforce https

     <rule name="CanonicalHostNameRule1" stopProcessing="true">
                        <match url="(.*)" />
                        <conditions logicalGrouping="MatchAny">
                            <add input="{HTTP_HOST}" pattern="^www\.maindomain\.com$" negate="true" />
                            <add input="{HTTPS}" pattern="off" />
                        </conditions>
                        <action type="Redirect" url="https://www.maindomain.com/{R:1}" />
                    </rule>