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

No worries - just copy and paste

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>

Share this Post: