URL Redirects with web.config

I have recently moved this blog from being hosted by WordPress over to the Hugo static site generator. As part of this move my blog URLs changed. I didn’t want to break any exiting links pointing to my blog so I wanted to setup some HTTP 300 permanent redirects. The site is hosted on an Azure app service, so I can use the web.config to redirect one URL to another.

I took me a while to track down the required config but I eventually opted for the following. I only had a handful of redirects to do so I just set up a rule for each:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

  <system.webServer>
    <rewrite>
      <rules>

        <rule name="rewrite1" stopProcessing="true">
          <match url="(.*)" />
          <conditions trackAllCaptures="true">
            <add input="{URL}" pattern="^/(2019\/01\/28\/unit-testing-entity-framework-dependencies)" />
          </conditions>
          <action type="Redirect" url="post/unit-testing-entity-framework" redirectType="Permanent" />
        </rule>

        <rule name="rewrite2" stopProcessing="true">
          <match url="(.*)" />
          <conditions trackAllCaptures="true">
            <add input="{URL}" pattern="^/(2018\/12\/03/swashbuckle-and-swagger-in-net-core)" />
          </conditions>
          <action type="Redirect" url="post/swashbuckle" redirectType="Permanent" />
        </rule>

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

</configuration>

A couple of notes:

  • Give each rule a unique name.
  • When adding a condition, the pattern uses a RegEx to match the URL. Hence why the forward slashed are escaped with a backwards slash: /

Another useful rule is to redirect from HTTP to HTTPS:

 <rule name="HTTP 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>
Alex Orpwood Written by:

Software developing and architecting for 20 years. Satellite monitoring by day, writing my own app by night. More about me