How to redirect http to https and www to non-www via web.config?

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x