(Last Updated On: March 15, 2018)

There seems to be a lot of information out there for URL Rewriting when it comes to using .htaccess files, but not a lot when using IIS and a web.config.

It’s a really simple task, it’s not something you do all the time, it’s a set and forget type operation. Put the snippet of code away for safe keeping for the next time you need it.

Here is what you need:

  • Internet Information Server IIS (current version is 10.0.x)
  • URL Rewrite extension installed – If you don’t have URL Rewrite installed, go to https://www.iis.net/downloads/microsoft/url-rewrite to download the installer or you can use Web Platform Installer to install the extension for you.
  • web.config file in your root directory of your application

I’m going to use our own website as the example of how to redirect. Here is how we redirect any non https requests to https:

<configuration>
	<system.webServer>    
		<rewrite>
			<rules>
				<rule name="Redirect to http" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
					<match url="*" negate="false" />
					<conditions logicalGrouping="MatchAny">
						<add input="{HTTPS}" pattern="off" />
					</conditions>
					<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Found" />
				</rule>
			</rules>
		</rewrite>	
	</system.webServer>
</configuration>
URL Rewrite for HTTP to HTTPS in web.config

The important lines to note are between lines 6 and 10.

Looking more closely:

<match url="*" negate="false" />
	<conditions logicalGrouping="MatchAny">
		<add input="{HTTPS}" pattern="off" />
	</conditions>
	<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Found" />

The Match: Match any incoming URL to our site “(.*)”

The Condition: If the HTTPS pattern is not on for the incoming URL the condition is met.

The Redirect: Redirect to requested host header {HTTP_HOST} but this time force https. Continue to pass any querystring from the original URL to the new URL {REQUEST_URL}.

Once you save the web.config – you can test your site immediately. If you have any caching turned on, don’t forget to hard refresh your browser.

Please note: You can use the GUI editor for URL Rewrite within IIS but often on remote servers, I don’t have access to that. So it’s good to know where the rewrite rules go.