Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL Rewrite to remove www and redirect to https using web-config (c# .net)

I have the following code in my web-config to be able to redirect both the URLs with the prefix "www" and non-SSL requests to the https:// mydomain.com because the SSL certificate is registered to the domain without the www

<rewrite>
  <rules>
    <rule name="Remove WWW prefix and redirect to https" >
      <match url="(.*)" ignoreCase="true" />
      <conditions logicalGrouping="MatchAny">
        <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" ignoreCase="true" />
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
      </conditions>
      <action type="Redirect" redirectType="Permanent" url="https://mydomain.com/{R:1}" />
    </rule>
  </rules>
</rewrite>

This is the result:

1) http:// mydomain.com/something --> https:// mydomain.com/something (Correct)

2) http:// www.mydomain.com/something --> https:// mydomain.com/something (Correct)

3) https:// www.mydomain.com/something --> Shows certificate error (There is a problem with this website's security certificate.)

When you select "Continue to this website (not recommended)." on the certificate error page, the url is rewritten correctly (https:// mydomain.com/something)

How can I make sure the certificate error does not show?

Thank you

like image 779
The Serious Game Programmer Avatar asked Apr 25 '14 08:04

The Serious Game Programmer


2 Answers

One way to solve it is to register two separate rules:

  1. Remove www.
  2. Force HTTPS.

    <rule name="Remove www" stopProcessing="true">
      <match url="(.*)" negate="false"></match>
      <conditions>
        <add input="{HTTP_HOST}" pattern="^www\.(.*)$" />
      </conditions>
      <action type="Redirect" url="https://{C:1}/{R:1}" appendQueryString="true" redirectType="Permanent" />
    </rule>
    <rule name="Force HTTPS" enabled="true">
      <match url="(.*)" ignoreCase="false" />
      <conditions>
        <add input="{HTTPS}" pattern="off" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
    </rule>
    
like image 193
Robertas Avatar answered Oct 24 '22 16:10

Robertas


so we use this in our projects, and this works.

Let me know it that helps:

<rewrite>
  <rules>
    <rule name="Redirect to https">
      <match url="(.*)"/>
      <conditions>
        <add input="{HTTPS}" pattern="Off"/>
        <add input="{REQUEST_METHOD}" pattern="^get$|^head$" />
        <add input="{HTTP_HOST}" pattern="localhost" negate="true"/>
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"/>
    </rule>
  </rules>
</rewrite>

It also ignores the request when you access the site on your local machine.

like image 41
Del Avatar answered Oct 24 '22 16:10

Del