asp.netiisweb-configiis-8.5

IIS Redirecting non-WWW to WWW along with HTTP to HTTPS ISSUE


I want to redirect non-WWW to WWW along with HTTP to HTTPS in IIS 8.5. if users type http://example.com, http://www.example.com, or https://example.com, they all redirect to https://www.example.com.

This is my web.config file

    <rewrite>
  <rules>
    <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.example.com/{R:1}" appendQueryString="true" redirectType="Permanent" />
    </rule>
  </rules>
</rewrite

Please note that in IIS i have ONLY 1 binding which is example.com, The problem is : for all the urls it redirects to https://www.example.com BUT the start page of IIS appears not my Default.aspx, and When i type https://www.example.com/Default.aspx it gives 404 Error.


Solution

  • You will need to bind each hostname to a website. Any hostnames not specifically bound to a website (or the servers IP address) will be handled by the Default Website in IIS (binding * - meaning any hostname not bound to a running Website).

    A nice easy setup is to create 2 Websites in IIS (lets call them Application and Rewrites) - one to host your application, a second to handle rewriting other domains to your primary domain. Any domain you bind to the Rewrite Website will redirect its traffic to https://www.example.com.

    ###Application Website

    ###Rewrite Website

    Create a web.config in the Rewrite Website webroot folder as follows:

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
      <system.webServer>
        <rewrite>
          <rules>
            <rule name="Redirect any traffic to Primary hostname" enabled="true" stopProcessing="true">
              <match url="(.*)" />
              <action type="Redirect" url="https://www.example.com/{R:1}" appendQueryString="true" redirectType="Permanent" />
            </rule>
          </rules>
        </rewrite>        
      </system.webServer>
    </configuration>
    

    Any traffic accessing http://example.com, https://example.com, or http://www.example.com will be redirected to https://www.example.com (including any path/query string)

    NOTE: You could use the default website as the Rewrite website, or move the wildcard * binding from the default website to a new Rewrite website - to redirect any domain to your https://www.example.com - however this is bad practise / not advised.

    Pre-requisite: To use this solution you'll need to install the IIS URL Rewrite extension if you don't have it installed already.