SkillAgentSearch skills...

UrlRewrite.Net

Replacement for the IIS Url Rewriter that fixes all the limitations in the Microsoft implementation

Install / Use

/learn @Bikeman868/UrlRewrite.Net
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

UrlRewrite.Net

Drop in replacement for the IIS Url Rewriter that removes all the limitations and perfromance constraints of the the Microsoft implementation. Drop this into your web site in place of the Microsoft Rewrite module and everything will work as before, but now you can extend, enhance and optimize your rules going forward.

Why use this?

  • Backward compatible with your existing IIS Rewriter module rules.
  • Removes all the limitations of the standard Microsoft rewriter module - see features below.
  • Order of magnitude faster than the standard Microsoft rewriter module because it is written to be very efficient, allows lists of rules to be inside a parent rule, and it supports faster comparison methods than RegEx.

Features

  • All the capabilities of the standard Microsoft IIS rewriter module. See http://www.iis.net/learn/extensions/url-rewrite-module/using-the-url-rewrite-module
  • Hierarchical rules, ie rules within rules. This allows you to short circuit rule evaluation.
  • Regex is supported for backward compatibility but much faster alternatives are provided.
  • Can modify query string parameters whereas the Microsoft one only provides an option to append the whole query string or not.
  • Ability to replace specific parts of the path or query string without the clunky regex back reference syntax.
  • Ability to insert and delete parts of the path and query string as well as delete all except type operations.
  • Register your own .Net classes as conditions, actions or operations allowing you to include complex business logic in your rewriter rules.
  • Integrates into your application with Dependency Injection.
  • Implemented as an IIS managed module.
  • All source code is in .Net so you can set break points and trace code if you want.
  • Provides a mechanism similar to the Microsoft Failed Request Trace module to trace rule execution.
  • Unless rules are set to 'Dynamic' the results of rule evaluation will be cached for subsequent requests.

Current status

Version 1.0.0 was functionally complete except for the caching of non-dynamic requests. This version was published to NuGet so that I can get feedback on backwards compatibility.

The standard IIS rewrite module is not very precisely documented so I need some people out there to try is with their rewrite rules and let me know where the behaviour is different between this Rewrite Module and the Microsoft one. I am aiming for 100% backwards compatibility.

If you are starting from scratch and don't need compatibility with an existing set of rewriter rules then go for it, this code is stable and production ready. I already have it on all of my own web sites and have started optimizing the performance of my rules.

Roadmap

  1. Estimated completion date for version 1.0 is end of May 2016.[ Actually completed end of April 2016]
  2. Caching of non-dynamic requests. This involves hashing the url and doing a lookup on the redirection results rather then re-evaluating the rules each time. If any of your rules produce different results each time they are run (because they lookup in a database, or use the current time of day for example) then be sure to mark them as Dynamic so that the results will not be cached.
  3. 100% unit test coverage.
  4. Outbound rules. This is a feature of the IIS rewriter that I only just discovered.
  5. Ability to rewrite the 'host' part of the request.

NuGet Package Versions

These are the versions that had major feature improvements or breaking changes you need to be aware of.

|Version|Comments| |---|---| |1.0.0|First production ready release April 2016| |1.0.1|Adds the handler to the web.config file when it is installed| |1.0.6|Added support for {} in literal values| |1.0.7|Rules have an enabled property - useful during testing and debugging| |1.1.0|BREAKING CHANGE - method signature of the Initialize() method changed to provide more flexibility in selecting which requests to trace| |1.1.1|BREAKING CHANGE - the default value for the stopProcessing attribute on the <rules> element changed from false to true| | |Added a value="my value" attribute to <rewrite>, <append> and <insert> as a shorthand for from="literal" fromIndex="my value"| |1.1.2|Added support for version 4.0 and 4.5 of the .Net Framework| |1.2.0|The IsFile and IsDirectory matchType now check for the existence of a physical file on disk| |1.2.1|Updated version number of dependant packages| |1.2.2|Trace log includes both values in comparison operations| |1.2.3|Made it easier to write your own custom parser by using IoC to construct actions and conditions| |1.2.4|Fixed bugs found by raerae1616 in https://github.com/Bikeman868/UrlRewrite.Net/issues/10 | |1.2.5|Fixed bug with macro expansion in literals | |1.2.6|Added support for negative indexes when appending to a path element| |1.2.7|Fixed a bug in the <insert> action which was expecting an index attribute rather than toIndex as documented. index still works for backward compatibility.|

Getting started

If you already use the Microsoft URL Rewriter module, follow these steps to replace it with this modue.

  1. Add a reference to the UrlRewrite.dll assembly. You can compile the source, or install the NuGet package UrlRewrite.Net.
  2. Add the Rewrite Module to your web.config file.
  3. Move your rewriting rules into a separate file (unless your config file is already set up like this).
  4. Initialize the Rewrite Module in your application startup code.

These steps are described in more detail below.

Install the Rewrite Module.

  1. In Visual Studio, go to the Tools Menu and choose "NuGet Package Manager" then "Package Manager Console"
  2. In the package manager console type Install-Package UrlRewrite.Net and press Enter.

Add the Rewrite Module to your web.config file.

Merge this into your web.config file

   <system.webServer>
     <modules runAllManagedModulesForAllRequests="true">
       <remove name="UrlRoutingModule" />
       <add name="UrlRoutingModule" type="UrlRewrite.RewriteModule, UrlRewrite" />
     </modules>
   </system.webServer>

Note that your web site needs to be running in Integrated Pipeline mode and not Classic. This is a setting on the App Pool in IIS.

Note that the NuGet package installer will attempt to make this change for you but I recommend that you check that the changes were made correctly.

Move your rewrite rules to a separate file

In .Net applications config files can store sections of the config file in separate files. If you have already configured your application like this, then then you should rename the file containig your rules to RewriteRules.config.

If you are starting from scratch then create a file called RewriteRules.config in the root folder of your web site and type your rules into it as described in the rest of this document.

If you use the Microsoft Url rewriter already and have the rules directly in your web.config file, then you will need to cut the <rewrite> section from your web.config file and paste them into a new file called RewriteRules.config. In this case if you want to be able to switch back to the Microsoft Url rewriter, then replace the <rewrite> section in your web.config which this:

    <rewrite configSource="RewriteRules.config" />

Initialize the Rewrite Module

The Rewrite Module must be initialized by your application before it will rewrite any requests. This is usually done in the Application_Start() method of Global.asax.cs.

Note that Global.asax runs after the Rewrite Module, so for the very first request to your web site the Rewrite Module will not rewrite the request. Until you initialize the Rewrite Module it does not know where the rules are, or how to construct your custom types.

To initialize the Rewrite Module call the static Initialize() method like this:

    void Application_Start(object sender, EventArgs e)
    {
	   UrlRewrite.RewriteModule.Initialize();
    }
   

The Initialize() method has optional parameters you can pass to customize its behaviour, these are described in more detail below.

Example rules

Note that these examples use made up sample data. Your rules must be written to match the URLs that your web site receives.

Example of a rules file that uses some of the most common syntax

Permanently redirects /company/quote/page3.aspx?date=now to /entity/quote/page3.aspx?date=now

Permanently redirects /company/profile/page1.aspx?date=now to /entity/profile/page1.aspx?date=now

Permanently redirects /company/financials/page2.aspx?date=now to /entity/financials/page2.aspx?date=now

Does not redirect /company/history/page1.aspx

Does not redirect /company/quote/page1

For any path like /company/.../*.aspx if the session belongs to a customer appends ?customer=true to the url

    <rewrite>
      <rules name="root">

        <assembly fileName="MyCompany.Rewrite">
          <class name="isCustomer" type="condition" className="MyCompany.Rewrite.Conditions.IsCustomer" />
        </assembly>
      
        <rule name="is a company page">
          <condition scope="pathElement" index="1" test="equals" value="company" />
          <condition scope="pathElement" index="-1" test="endsWith" value=".aspx" />
          <rules name="company page rules>
            <rule name="permanently redirect urls from v1 site">
              <conditions logicalGrouping="matchAny">
                <condition scope="pathElement" index="2" test="equals" value="quote" />
                <condition scope="pathElement" index="2" test="equals" value="profile" />
                <condition scope="pathElement" index="2" test="equals" value="financials" />
              </conditions>
              <rewrite to="pathElement" toIndex="1" from="literal" fromIndex

Related Skills

View on GitHub
GitHub Stars59
CategoryDevelopment
Updated6mo ago
Forks15

Languages

C#

Security Score

72/100

Audited on Oct 2, 2025

No findings