9

I would like to use web.config to redirect all requests on my asp.net site to https:// with non-www. That is:

http://
http://www
https://www

should all go to

https://

So far I have this for my web.config:

<system.webServer>
...
 <rewrite>
   <rules>
     <clear />
     <rule name="Redirect to https" stopProcessing="true">
       <match url=".*" />
       <conditions>
         <add input="{HTTPS}" pattern="off" ignoreCase="true" />
       </conditions>
       <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
     </rule>
   </rules>
 </rewrite>
</system.webServer>

The above snippet takes care of redirecting these two:

http://
http://www

But I'm missing the last, which is:

https://www  --->  https://

How to do that?

brinch
  • 2,544
  • 7
  • 33
  • 55

2 Answers2

7

You need to add second rule:

<rule name="NonWwwRedirect"  stopProcessing="true"> 
    <match url="(.*)" /> 
    <conditions> 
        <add input="{HTTP_HOST}" pattern="^www.sitename\.com$" /> 
    </conditions> 
    <action type="Redirect" url="http://sitename.com/{R:1}" /> 
</rule> 

You just need to replace sitename.com with your domain name

Victor Leontyev
  • 8,488
  • 2
  • 16
  • 36
  • 1
    Old post I know. I'm trying to do a http --> https as well as a www --> non-www. Should the `action url="http://......."` not be `action url="https://...."`? Since the OP was wanting https redirect as well? – Rob Scott Nov 10 '20 at 00:19
  • In .NET Core 3.1 in every client I receive ERR_TOO_MANY_REDIRECTS – Александър К. Jul 05 '21 at 21:27
3

Here´s a generic rule that worked for me:

<rule name="Force non-WWW" enabled="true" stopProcessing="true">
    <match url="(.*)" />
    <conditions logicalGrouping="MatchAny">
        <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
    </conditions>
    <action type="Redirect" url="http://{C:2}/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>
Jorge Mauricio
  • 411
  • 6
  • 18