Developing Clearly Adventures in Coding and IT

Three Web.config tricks – force HTTPS, force yes/no www subdomain

T

No worries series is designed to do just that – enable you to say “no worries”, just copy the code and fire it up. For the first post in the series, we’ll do two simple, but very common requirements using some web.config tricks. So, let’s get into it.

Force HTTPS

<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>

Sometimes you’ll get a requirement to have content available only through www subdomain or without it.

Remove www subdomain

<system.webServer>
<rewrite>
<rules>
<clear />
<rule name="Remove www" stopProcessing="true">
<match url="(.*)" ignoreCase="true" />
<conditions logicalGrouping="MatchAll">
<add input="{HTTP_HOST}" pattern="^www\.(.+)$" />
</conditions>
<action type="Redirect" url="http://{C:1}/{R:0}" appendQueryString="true" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>

Enforce www subdomain

<system.webServer>
<rewrite>
<rules>
<rule name="Enforce www">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" pattern="^www\.YOURDOMAIN\.com$" negate="true" />
</conditions>
<action type="Redirect" url="http://www.YOURDOMAIN.com/{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>

About the author

Domagoj

IT Consultant. I make Web-Based Systems and Apps work. Working with web technologies for as long as I can remember. Humanist. Liberal. Progressive. Occasional blogger. Opinions posted anywhere on the web are my own.

Add comment

By Domagoj
Developing Clearly Adventures in Coding and IT

Categories

Recent Posts

Recent Comments

Follow Me