Redirect HTTP to HTTPS along with WWW or Without WWW using web.config

ASP.NET Comments Off on Redirect HTTP to HTTPS along with WWW or Without WWW using web.config

After Google has recommended to use SSL in all your websites that collect personal data. Most of the major websites are implementing SSL – secure socket layer for their websites.
You can buy a cheap SSL from namecheap.com or Get a free SSL from Let’s Encrypt

If you install SSL for your website and want to force all the URL’S to redirect to https protocol, we can do this very simply in web.config file utilizing IIS RE-WRITE MODULE. Utilizing iis rewrite module issues a 301 – permanent redirect even before the aspx pages are called.

I am posting here 2 snippets that redirect http to https with and without www.

http to https with www

         <system.webServer>
  

    <rewrite>
      <rules>
        <rule name="HTTP Redirect to HTTPS" enabled="true" stopProcessing="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>

        <rule name="Redirect to WWW" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{HTTP_HOST}" pattern="^site.com$" />
          </conditions>
          <action type="Redirect" url="https://www.site.com/{R:0}" redirectType="Permanent" />
        </rule>



      </rules>
    </rewrite>
  </system.webServer>

In the above snippet, the first rule redirects all the URL’S with http to https. The second rule redirects all the url to force include www.

http to https without www

         <system.webServer>
  

    <rewrite>
      <rules>
        <rule name="HTTP Redirect to HTTPS" enabled="true" stopProcessing="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>

        <rule name="Redirect to non-WWW" stopProcessing="true">
			  <match url="(.*)" negate="false"></match>
			  <action type="Redirect" url="https://site.com/{R:1}"></action>
			  <conditions>
				  <add input="{HTTP_HOST}" pattern="^site\.com$" negate="true"></add>
			  </conditions>
		  </rule>



      </rules>
    </rewrite>
  </system.webServer>

In the above snippet, the first rule redirects all the URL’S with http to https. The second rule redirects all the url to force omit www (redirecting without www).

Make sure you installed IIS re-write module for this in your IIS.



Author

Search

Back to Top