Translation: Creating rewrite rules for URL Rewrite modules

Source: Internet
Author: User
Tags servervariables

Original name: Creating Rewrite Rules for the URL Rewrite Module

Original address: Http://www.iis.net/learn/extensions/url-rewrite-module/creating-rewrite-rules-for-the-url-rewrite-module

Original Ruslan Yakushev

The URL Rewrite module is a downloadable extension of the IIS server that is pre-installed in Windows Azure Web Sites (waws) and can be used directly. This walkthrough will lead you through the creation and validation of a series of commonly used URL rewrite rules.

Front-facing conditions

The following conditions are required for this walkthrough:

1. IIS7 or later, the ASP. NET service must be enabled.

2. The URL Rewrite module is already installed, as detailed in the following: Using the URL Rewrite module.

Create a test page

The following exercise will use the default configuration for IIS, and the default Web site will be in the%systemdrive%\inetpub\wwwroot\ folder.

To demonstrate how the URL Rewrite module works, we will create a simple ASP. Page that reads the Web Server's variables and prints its values to the page.

In the Wwwroot folder, create a file named Article.apsx, and copy the following ASP. NET code into this file.

<%@ Page Language="C #" %><!DOCTYPE HTML Public "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd "><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" /><title>URL Rewrite Module Test</title></Head><Body>      <H1>URL Rewrite Module Test Page</H1>      <Table>            <TR>                  <th>Server Variable</th>                  <th>Value</th>            </TR>            <TR>                  <TD>Original URL:</TD>                  <TD><%=request.servervariables["Http_x_original_url"] %></TD>            </TR>            <TR>                  <TD>Final URL:</TD>                  <TD><%=request.servervariables["Script_name"] + "?" +request.servervariables["query_string"] %></TD>            </TR>      </Table></Body></HTML>

After saving, access http://localhost/article.aspx in the browser to confirm that the page content can be seen correctly in the browser.

Creating rewrite rules

We will create the following simple rewrite rules.

Original address: Http://localhost/article/342/some-article-title

After rewriting

Destination Address: Http://localhost/article.aspx?id=342&title=some-article-title

We will use the URL Rewrite management interface in IIS Manager to create rewrite rules, please refer to the following steps:

1. Open IIS Manager

2. Select the Default Web Site

3. In the features view, click the URL Rewrite

4. In the Action panel on the right, click Add Rules ... Add rule

5. In the Add Rules Adding Rule dialog box, select Blank Rule, then click OK.

You can now define the actual rewrite rules. In the URL Rewrite module, each rewrite rule must provide the following four information:

1. Rule name

2. Match the regular expression template for the target URL.

3. Conditional options

4. Actions that need to be taken in case the template matches and the condition is set.

Management rules

In the Name text box, enter a unique rule name, for example: "Rewrite to Article.aspx"

Define a matching regular expression

In the Pattern Match template text box, enter the following regular expression.

^article/([0-9]+)/([_0-9a-z-]+)

This is a regular expression that will match the many URL addresses that meet the following rules.

1. The starting character sequence is "article/"

2. After the first/after, contains one or more numeric characters

3. In the second/after, contains one or more letters, numbers, underscores or hyphenation lines.

Note that parentheses are used in regular expressions, and parentheses are used to create a capturing group, which can be used later by a reverse reference.

Defining actions

Because the rule we define wants to rewrite the URL, select the Rewrite override action type in the action Type drop-down list box, and in the override Target's Rewrite URL input box, enter the following content.

Article.aspx?id={r:1}&title={r:2}

Here we use some variables to rewrite the URL, note that in the query string we used {r:1} and {r:2}, which are the reverse references just mentioned.

For other settings We use the default values so that the entire editing rule page should look like the following.

In the right panel, click Apply to save the rule.

To view rewrite rules in a configuration file

The rewrite rules that we define will be saved in applicationhost.config or Web. config. To see the rewrite rule that we just created, open the Web. config file in%systemdrive%\inetpub\wwwroot\, and you should see the following in the <rewrite> configuration section.

<rewrite>  <rules>    <Rulename= "Rewrite to Article.aspx">      <MatchURL= "^article/([0-9]+)/([_0-9a-z-]+)" />      <Actiontype= "Rewrite"URL= "Article.aspx?id={r:1}&amp;title={r:2}" />    </Rule>  </rules></rewrite>

The syntax above also applies to Web. config in Windows Azure Web Sites (waws).

Test rewrite rules

Open the browser and type in the Address bar: Http://localhost/article/234/some-title

You'll see in the page that the server's rewrite rules modify the URL to Article.aspx, and 234 and "Some-title" are passed as query parameters.

Create a redirect rule

Below we create a redirect rule.

Source Address: http://localhost/blog/some-other-title/543

Directed to: Http://localhost/article/543/some-other-title

Redirection rules can direct multiple URL addresses to the same address page.

Open the IIS Manager URL Rewrite Properties window and click Add Rule (s) ... To add a rule, select the blank rule empty template again.

On the Edit Rule page, enter the following:

1. Rule name: Redirect from blog (this is the unique name of the rule)

2. Matching Template: ^blog/([_0-9a-z-]+)/([0-9]+) (this template is used to match the address beginning with the blog, capturing the second and third sections for the reverse reference)

3. Action: Redirect (redirect action causes a Redirect response to be sent to the browser)

4. Purpose Url:article/{r:2}/{r:1} (this template is used for redirection, note that the previous capturing group is used here using a reverse reference)

The interface after the input should be as follows.

After entering the redirect URL.

Other configurations remain the same, click Apply Application rules in the right panel.

Test redirection rules

Open a browser and enter it in the Address bar: http://localhost/blog/some-other-title/323

In the browser, you will see that the address is redirected to Http://localhost/article/323/some-other-title.

Create an access restriction rule

The third rule, we will block the request without a specific request header. This rule can be used to block hacker attacks that use IP addresses instead of host names.

This time, instead of using the IIS Manager to create the rule, we created the rule directly in the Web. config in%systemdrive%\inetpub\wwwroot\. Locate the <rewrite> configuration section and insert the new content first in the Rules section so that the new rule becomes a rule in the rule set.

<Rulename= "Fail Bad Requests">      <MatchURL=".*"/>      <conditions>        <Addinput= "{http_host}"pattern= "localhost"negate= "true" />      </conditions>      <Actiontype= "Abortrequest" /></Rule>

Now all of the rewrite rules are as follows.

<rewrite>  <rules>    <Rulename= "Fail Bad Requests">      <MatchURL=".*"/>      <conditions>        <Addinput= "{http_host}"pattern= "localhost"negate= "true" />      </conditions>      <Actiontype= "Abortrequest" />    </Rule>    <Rulename= "Redirect from blog">      <MatchURL= "^blog/([_0-9a-z-]+)/([0-9]+)" />      <Actiontype= "Redirect"URL= "Article/{r:2}/{r:1}"Redirecttype= "Found" />    </Rule>    <Rulename= "Rewrite to Article.aspx">      <MatchURL= "^article/([0-9]+)/([_0-9a-z-]+)" />      <Actiontype= "Rewrite"URL= "Article.aspx?id={r:1}&amp;title={r:2}" />    </Rule>  </rules></rewrite>

Understand the rules you just defined.

<url= ". *"/>

This matching rule says we're going to match any URL.

<input= "{http_host}"  pattern= "localhost"  negate  = "true"/>

This element creates a condition for the rule by reading the http_host to get the host part of the request address, matching localhost, and then inverting. In other words, this condition checks that the Host in the request address does not contain localhost.

<type= "abortrequest"/>

This action aborts the processing of the request.

Testing restricted access rules

Open the browser and access our server via Ip address: Http://127.0.0.1/article/234/some-title, you should not get any response from the server. If you use Http://localhost/article/234/some-title, the access should be successful.

Unsuccessful access results are as follows.

And the successful visit is as follows.

Summarize

In this walkthrough, we learned how to create a URL Rewrite rule, either through the IIS manager or manually. This walkthrough demonstrates the main uses of the URL Rewrite module, such as the support for regular expressions, and the conditions for overriding by using HTTP request header information and server variables.

Translation: Creating rewrite rules for URL Rewrite modules

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.