Creating a rewrite rule

Overview

This article aims to describe the steps on how to create a Rewrite rule through IIS or the web.config file. Rewrite rules can be written to generate URLs that can be easier for users to remember, simple for search engines to index, and allow URLs to follow a consistent and canonical hostname format. 

Prerequisites

  • Knowledge of IIS redirects and basic regular expressions.

 

Solution

  1. Go to the IIS Manager.
  2. Select your site.
  3. In the Feature view, click URL Rewrite.
    • If you don't see the URL Rewrite module, you can download it from here.
  4. In the Actions pane, on the right side, click on Add rules 
  5. Select the Blank Rule template. 
  6. The Edit Inbound Rule screen will open so you can customize the redirection rule. 
  7. You can follow this article, in order to have a better understanding of how to create the rules.

This is stored on an XML file called web.config, you can also edit that file and set up the rule on an XML format. Such as:

<rule name="Spanish Redirect" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAny" trackAllCaptures="true">
<add input="{HTTP_HOST}" pattern="website.es" />
</conditions>
<action type="Redirect" url="https://website.com/es/{R:0}" redirectType="Permanent" />
</rule></rule>

Custom Redirect Rules

 Redirecting from a path to a subdomain

  • From any page in www.domain.com/Path1
  • To http://www.path.domain.com/
<rule name="Path to Subdomain" stopProcessing="true">
      <match url=".*" />
      <conditions>
          <add input="{HTTP_HOST}" pattern="www.domain.com" />
          <add input="{PATH_INFO}" pattern="/Path1.*" />
      </conditions>
      <action type="Redirect" url="http://www.path.domain.com/" />
</rule>

Redirecting from a domain except for certain paths

  • From any page in www.domain.com
    • Except for www.domain.com/Path1
  • To https://www.anotherdomain.com/
<rule name="All except Path to Another Domain" stopProcessing="true">
      <match url=".*" />
      <conditions>
          <add input="{HTTP_HOST}" pattern="www.domain.com" />
          <add input="{PATH_INFO}" pattern="/(Path1).*" negate="true" />
      </conditions>
      <action type="Redirect" url="https://www.anotherdomain.com/" />
</rule>

 

For more information about the XML and how could you change it, please go to this link.

 

Testing

To verify the rewrite is working correctly, you must try to visit the old URL to see if you are redirected to the new URL from the browser.

 

Related Articles

Configure URL Redirects

Redirects and Their Functionality in DNN

Redirection error redirected you too many times

Comments

0 comments

Please sign in to leave a comment.