URLRewrite and IIS: Part Two – Introduction to “rewrite”

This is the second in our series about URLRewrite. We are going to focus on another aspect of URLRewrite. Namely the concept of rewriting a url “in-flight” to allow a URLRewrite rule to conduct an action that the administrator wishes to implement on the IIS server.

The subject of rewrites versus redirects immediately comes to mind. As I have worked over the years with IIS and URLRewrite, I found it far easier to use redirect rules, but these come with a penalty, since an incoming request causes additional overhead in the form of a new HTTP request being sent the server. Ideally, if you can avoid this, you should use a Rewrite rule to change the incoming request on the fly rather than overt redirect. The rewrite rule we are going to show you is a “redirect in disguise” and accomplishes the task of a redirect on one succinct operation rather than two.

Lets design the use-case:

Imagine we have a directory on a web site and this directory is no longer used, but you want to inform your users that the directory has been retired. What to do?

In a standard redirect rule, you would match on a particular directory and then redirect to the retired page as follows (Note, we are going to use “/docs” as the example directory that is no longer valid):

Conditionals for redirect rule

 

Action for redirect rule.

The code that is placed into the web root “web.config” file looks like this:

<rule name=”Example Redirect” patternSyntax=”ECMAScript” stopProcessing=”true”>
<match url=”(.*)” />
<action type=”Redirect” url=”/retired.html” />
<conditions logicalGrouping=”MatchAny”>
<add input=”{PATH_INFO}” pattern=”^/docs/(.*)” />
<add input=”{PATH_INFO}” pattern=”/docs” />
</conditions>
</rule>

When run in the browser, the following occurs:

Result of redirect run. Note that the URL changed to point to the “retired.html” page.

 

The rule fires and redirects to the expected url and is shown in the browser.

Note that in this rule, there are two conditions, either of which, when run, will perform the redirect. The first is to match any and all sub-directories of “docs”, while the second rule handles the case where the url of “http:/someserver/docs” is handled as a specific case of it’s own. I am absolutely certain some of you will comment on there being better ways to do this in this example, but for purposes of clarity, this is the format I chose to use. If you do want to send in examples of better ways to do this, visit the “contact” link and I will share your comments and ideas in future articles. Remember, I’m learning everyday too and there is ALWAYS a better way to do things ;>)

So… Our redirect example above is really pretty good. It handles the full range of references to references to the “/docs” directory and sub-directories. But is there a better way to do it? Let’s try the “rewrite” option and see what happens (after first disabling the prior example!):

Conditional at the URL section
Action clause for the rewrite rule.

The code that is placed into the web root “web.config” file looks like this:

<rule name=”Example Rewrite” stopProcessing=”true”>
<match url=”^docs/(.*)$” />
<action type=”Rewrite” url=”/retired.html” />
</rule>

Now let’s execute this rule:

The page loads the same “retired.html” as before, but the URL remains the same on the browser URL bar!

 

This is a three for one benefit. The browser doesn’t have to incur local overhead on a redirect. The server doesn’t have to work harder and the apparent URL doesn’t change on the client end. It is all handled at the server end of things.

Isn’t this a little more efficient? It does everything needed in four lines and with a single transaction. In truth, the redirect rule could have been more efficient, but again, for purposes of clarity, we want to get you to think in new ways about URLRewrite and to, as the character “Morpheous” says in “The Matrix” says, “free your mind”. A hint is to look at the line “<match url=”^docs/(.*)$” />” and perhaps try your own experiments with the redirect. That is the other thing with URLRewrite and, for that matter, mod_rewrite in Apache webservers. You want to try new rules, new ideas and play with them to get a good feel for what works and what does not. Experiment and don’t be afraid to fail.

Back to the rewrite rule. It is efficient and small. The minor penalty for the in-flight rewrite is less than what would be incurred against a redirect rule and provides a first taste of what can be done.

In truth, this is a small taste of the many things the rewrite rules can be used for. We will be covering more rewrite examples in coming articles and also discussing back-references and URLRewrite. These are extremely powerful and useful for helping to construct new urls and are a staple tool you will need to learn to effectively use URLRewrite.

Until next time!

Using IIS URLRewrite – Part 1

One of the tools I use with IIS 7.5 and 8.0 as a web administrator and designer to add functionality to applications like content management systems, document management systems and static web sites is to use URLRewrite.

This module is freely available from Microsoft and allows for creation of unique rules and processing of incoming and outgoing requests on the fly.

So what can it do? Most often, it allows for very simple handling of URL requests using simple to advanced rules that are accessible via the IIS Manager tool or by direct editing of the web.config file hosted under the web site for which the rules will be applied.

The most common rules URLRewrite is used for is for redirects based on one or more criteria.

In this first article, we will test two specific cases

  1. Single URL Redirect.
  2. Multiple Conditional Match Redirect

Single URL Redirect

Imagine a case where you want a specific page that is available on the web root of a site to no longer be accessible. You may want to use the page later, but you simply need a quick and dirty rule to redirect the page until you need it again later.

Since I use PHP often, I occasionally like to use a classic page called “phpinfo.php” to look at the site environment variables for my site. But it is dangerous to leave this file unprotected since it can give anyone a deep look into your site specifics. So, it makes sense to add a rule to deactivate access to the file until there is a need to use it.

The first step is to insure that URLRewrite is installed. To do so, make sure you have installed IIS on your system along with the IIS Manager tool and then install the “Web Platform Installer” per the instructions from Microsoft.

This tool allows IIS to install a wide range of add-ons from PHP to Perl and of course, URLRewrite 2.0. Simply follow the instructions and once it is installed, then launch Web Platform Installer. See the red colored icon under “Management” to launch the installer:

Launch the Web Platform Installer.

Type “URL” in the search bar and choose URLRewrite 2.0 and press “Add” – Note: In this photo, I have already installed URLRewite.
Type “URL” in the search bar and choose URLRewrite 2.0 and press “Add” – Note: In this photo, I have already installed URLRewite.
URL Rewrite Icon at the Site Level

Double-Click the icon to launch URL Rewrite and examine the screen. There will be no rules installed and the utility is waiting for it’s first rule to be added.

Let’s get back to the phpinfo.php rule.

We want to take any request coming into this site where the file “phpinfo.php” is referenced and to redirect it to another web site.

There are two ways to do this:

  1. From the IIS Manager screen with URL Rewrite Module administration.
  2. Or… by editing the web.config file at the site root.

Let’s start by doing the rule addition with the first option via the GUI. Add a new rule by clicking “Add Rule(s)” at the top right of the screen.

Next, choose “Blank rule” and press “OK”.

Give the rule a name. In this case called it “Example of Redirect”.

Make the following settings:

  • Under “Match URL”  set “Requested URL:” to “Matches the Pattern” and “Using” to “Exact Match”
  • In the “Pattern” box, type “phpinfo,php” or a file in your web root that you wish to redirect.
  • Under “Action”, chose “Action type” of “Redirect”
  • Under “Redirect URL:” enter a URL of choice. I entered http://www.google.com for the URL to redirect to.
  • Now click “Apply” on the top far right.
  • The rule is built and ready to use.
  • Enter the URL http://localhost/phpinfo.php (or whatever site url is appropriate) and your rule should activate.
This rule allows for matching of a single URL to redirect to a new location or site.

If you have trouble making the rule work, go back and check your entries for typos or not selecting the right drop down.

Now, go check your web.config file by editing with notepad or similar editor. You should see the following fragment:

<rule name=”Example of Redirect” enabled=”true” patternSyntax=”ExactMatch” stopProcessing=”true”>
                    <match url=”phpinfo.php” />
                    <conditions logicalGrouping=”MatchAll” trackAllCaptures=”false” />
                    <action type=”Redirect” url=”http://www.google.com” />
</rule>

You can also just cut and paste this into the web.config file as follows:

<?xml version=”1.0″ encoding=”UTF-8″?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <clear />

<rule name=”Example of Redirect” enabled=”true” patternSyntax=”ExactMatch” stopProcessing=”true”>
            <match url=”phpinfo.php” />
             <conditions logicalGrouping=”MatchAll” trackAllCaptures=”false” />
              <action type=”Redirect” url=”http://www.google.com” />
</rule>

</rules>
 </rewrite>

    </system.webServer>
</configuration>

Multiple Conditional Match Direct

Let’s try a different rule. First, we want to go to URLRewrite  at the site list of icons and double click it. Let’s deactivate the first rule we did above. Highlight “Example of Redirect” and then on the right Actions menu, click “Disable Rule”. This is done to prevent it from firing because we are trying a new way to disable the phpinfo.php file from being accessed and to redirect it.

Second rule example

Like we did before, add a new blank rule. Call this one “Example of Redirect with multiple conditions”.

Enter the following:

  • Under “Match URL”, select “Matches the Pattern” for Requested URL and “Regular Expressions” for “Using:”
  • In the “Pattern” box enter (.*)
  • Under Conditions click “Add”
  • For Condition input type {SCRIPT_NAME}
  • For Check if input string: “Matches the Pattern”
  • Under pattern, enter “phpinfo.php”
  • Click OK to close.

Add a new blank condition rule:

  • Under “Match URL”, select “Matches the Pattern” for Requested URL and “Regular Expressions” for “Using:”
  • In the “Pattern” box enter (.*)
  • Under Conditions click “Add”
  • For Condition input type {SCRIPT_NAME}
  • For Check if input string: “Matches the Pattern”
  • Under pattern, enter “somefile.html”
  • Click OK to close.
  • Look under “Conditions” for “Logical grouping” and select “Match Any”

Move down to the “Action” section of the rule

  • Under “Action”, chose “Action type” of “Redirect”
  • Under “Redirect URL:” enter a URL of choice. I entered http://www.google.com for the URL to redirect to.
  • Now click “Apply” on the top far right.
  • The rule is built and ready to use.
  • Enter the URL http://localhost/phpinfo.php or the second URL for the second file – http://localhost/somefile.html.

What should happen is that you can test one of the two files to redirect to the URL you like.

Again, if the rule did not work, then you need to examine the settings and adjust as needed.

You can also cut and paste this code into the web.config file:

<?xml version=”1.0″ encoding=”UTF-8″?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <clear />
                <rule name=”Rewrite test”>
                    <match url=”^article/([0-9]+)/([_0-9a-z-]+)” />
                    <conditions logicalGrouping=”MatchAll” trackAllCaptures=”false” />
                    <action type=”Rewrite” url=”article.aspx?id={R:1}&amp;title={R:2}” />
                </rule>
                <rule name=”wordpress” patternSyntax=”Wildcard”>
                    <match url=”*” />
                    <conditions logicalGrouping=”MatchAll” trackAllCaptures=”false”>
                        <add input=”{REQUEST_FILENAME}” matchType=”IsFile” negate=”true” />
                        <add input=”{REQUEST_FILENAME}” matchType=”IsDirectory” negate=”true” />
                    </conditions>
                    <action type=”Rewrite” url=”index.php” />
                </rule>
                <rule name=”Example of Redirect” enabled=”false” patternSyntax=”ExactMatch” stopProcessing=”true”>
                    <match url=”phpinfo.php” />
                    <conditions logicalGrouping=”MatchAll” trackAllCaptures=”false” />
                    <action type=”Redirect” url=”http://www.google.com” />
                </rule>
                <rule name=”Example of Redirect with multiple conditions” enabled=”true” patternSyntax=”ECMAScript” stopProcessing=”true”>
                    <match url=”(.*)” />
                    <conditions logicalGrouping=”MatchAny” trackAllCaptures=”false”>
                        <add input=”{SCRIPT_NAME}” pattern=”phpinfo.php” />
                        <add input=”{SCRIPT_NAME}” pattern=”404.shtml” />
                    </conditions>
                    <action type=”Redirect” url=”http://www.bing.com” />
                </rule>
            </rules>
        </rewrite>

    </system.webServer>
</configuration>

What have we learned?

In this lesson, we have learned how to configure URLRewrite and to test two rules. One with a single redirect based on a simple configuration and another using multiple conditions to be matched to fire the rule.

This is simply an introduction and we’ll cover an example of a Rewrite operation and also other useful operations that any web administrator would find useful in the next article.