Search code examples
http-redirecthttpsweb-config

How can I exclude specific subdomains from redirect to HTTPS in web.config?


I'm working on an MVC project, and I have the following working rule in my web.config, but it's redirecting all the subdomains to https. What I would like to do is to exclude some specific subdomains. For example, I need to redirect "mywebsite.com" and "www.mywebsite.com", but not "test.mywebsite.com" or "beta.mywebsite.com". The excluded subdomain should remain as "http://test.mywebsite.com" and "http://beta.mywebsite.com" without being redirected to https. How can I do that? Here's my rule in web.config:

<rule name="Redirect to https" stopProcessing="true">
  <match url=".*" />
  <conditions>
    <add input="{HTTPS}" pattern="off" ignoreCase="true" />
    <add input="{REQUEST_URI}" negate="true" pattern="^/\.well-known/pki-validation/(.*)$" ignoreCase="true" />
  </conditions>
  <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="true" />
</rule>

Solution

  • I used to have a similar configuration had used a rule along this line:

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <system.webServer>
            <rewrite>
                <rules>
                    <rule name="redirect to https2" stopProcessing="true">
                        <match url="^" ignoreCase="false" />
                        <conditions logicalGrouping="MatchAll">
                            <add input="{HTTP_HOST}" pattern="^subdomain\.example\.com$" negate="true" />
                            <add input="{HTTPS}" pattern="off" ignoreCase="false" />
                        </conditions>
                        <action type="Redirect" url="https://{HTTP_HOST}{URL}" redirectType="Found" appendQueryString="true" />
                    </rule>
                </rules>
            </rewrite>
        </system.webServer>
    </configuration>