Url Rewrite[转]

from:http://www.codeproject.com/KB/aspnet/urlrewriter.aspx

Introduction

One of the most popular extensions to the Apache webserver has been mod_rewrite - a filter which rewrites URLs. For example, instead of a URL such as

 Collapse Copy Code

http://www.apache.org/BookDetails.pl?id=5

you could provide a filter which accepts URLs such as

 Collapse Copy Code

http://www.apache.org/Book/5.html

and it will silently perform a server-side redirect to the first URL. In this way, the real URL could be hidden, providing an obfuscated facade to the web page. The benefits are easier to remember URLs and increasing the difficulty of hacking a website.

Mod_rewrite became very popular and grew to encompass a couple of other features not related to URL Rewriting, such as caching. This article demonstrates URL Rewriting with ASP.NET, whereby the requested URL is matched based on a regular expression and the URL mappings are stored in the standard ASP.NET web.config configuration file. ASP.NET includes great caching facilities, so there's no need to duplicate mod_rewrite's caching functionality.

As more and more websites are being rewritten with ASP.NET, the old sites which had been indexed by google and linked from other sites are lost, inevitably culminating in the dreaded 404 error. I will show how legacy ASP sites can be upgraded to ASP.NET, while maintaining links from search engines.

ASP.NET support for URL Rewriting

ASP.NET provides very limited support out of the box. In fact, it's support is down to a single method:

 Collapse Copy Code

void HttpContext.RewritePath(string path)

which should be called during the Application_BeginRequest() event in the Global.asax file. This is fine as long as the number of URLs to rewrite is a small, finite, managable number. However most ASP sites are in some way dynamic, passing parameters in the Query String, so we require a much more configurable approach.

The storage location for all ASP.NET Configuration information is the web.config file, so we'd really like to specify the rewrites in there. Additionally, .Net has a fast regular expression processor, giving free and fast search and replace of URLs. Let's define a section in the web.config file which specifies those rewrites:

 Collapse Copy Code

<configuration>
  <system.web>
        <urlrewrites>
            <rule>
                <url>/urlrewriter/show\.asp</url>
                <rewrite>show.aspx</rewrite>
            </rule>
            <rule>
                <url>/urlrewriter/wohs\.asp</url>
                <rewrite>show.aspx</rewrite>
            </rule>
            <rule>
                <url>/urlrewriter/show(.*)\.asp</url>
                <rewrite>show.aspx?$1</rewrite>
            </rule>
            <rule>
                <url>/urlrewriter/(.*)show\.html</url>
                <rewrite>show.aspx?id=$1&amp;cat=2</rewrite>
            </rule>
            <rule>
                <url>/urlrewriter/s/h/o/w/(.*)\.html</url>
                <rewrite>/urlrewriter/show.aspx?id=$1</rewrite>
            </rule>
        </urlrewrites>
    </system.web>
</configuration>

Notice how we have to escape the period in the url element such as 'show\.asp'. This is a Regular Expression escape and it's a small price to pay for the flexibility of regular expressions. These also show how we set-up a capturing expression using (.*) in the<url> element and refer to that capture in the <rewrite> element with $1

Configuration Section Handlers

.Net's configuration mechanism requires us to write code as a "handler" for this section. Here's the code for that:

 Collapse Copy Code

<configuration>
    <configSections>
        <sectionGroup name="system.web">
          <section name="urlrewrites" type="ThunderMain.URLRewriter.Rewriter,
              ThunderMain.URLRewriter, Version=1.0.783.30976,
              Culture=neutral, PublicKeyToken=7a95f6f4820c8dc3"/>
        </sectionGroup>
    </configSections>
</configuration>

This section handler specifies that for every section called "urlrewrites", there is a class calledThunderMain.URLRewriter.Rewriter which can be found in the ThunderMain.URLRewriter.dll assembly with the given public key token. The public key token is required because this assembly has to be placed into the GAC and therefore given a strong name.

A section handler is defined as a class which implements the IConfigurationSectionHandler interface. This has one method,Create(), which should be implemented, and in our code that is very simple. It merely stores the urlrewrites element for later use:

 Collapse Copy Code

public object Create(object parent, object configContext, XmlNode section)
{
    _oRules=section;

    return this;
}

Initiating the rewrite process

Coming back to actually rewriting the URL, as I said earlier, we need to do something in the Application_BeginRequest() event in Global.asax - we just delegate this to another class:

 Collapse Copy Code

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    ThunderMain.URLRewriter.Rewriter.Process();
}

which calls the static method Process() on the Rewriter class. Process() first obtains a reference to the configuration section handler (which happens to be an instance of the current class) and then delegates most of the work to GetSubstitution() - an instance method of this class.

 Collapse Copy Code

public static void Process()
{
    Rewriter oRewriter=
       (Rewriter)ConfigurationSettings.GetConfig("system.web/urlrewrites");

    string zSubst=oRewriter.GetSubstitution(HttpContext.Current.Request.Path);

    if(zSubst.Length>0) {
        HttpContext.Current.RewritePath(zSubst);
    }
}

GetSubstitution() is just as simple - iterating through all possible URL Rewrites to see if one matches. If it does, it returns the new URL, otherwise it just returns the original URL:

 Collapse Copy Code

public string GetSubstitution(string zPath)
{
    Regex oReg;

    foreach(XmlNode oNode in _oRules.SelectNodes("rule")) {
        oReg=new Regex(oNode.SelectSingleNode("url/text()").Value);
        Match oMatch=oReg.Match(zPath);

        if(oMatch.Success) {
            return oReg.Replace(zPath,
                             oNode.SelectSingleNode("rewrite/text()").Value);
        }
    }

    return zPath;
}

Installing the sample code

Extract the code into a URLRewriter folder, then turn this into a virtual directory using the Internet Information Services MMC control panel applet. Compile the code use the 'Make Rewriter.bat' batch script into the bin sub-folder. Then addbin/ThunderMain.URLRewriter.dll to the Global Assembly Cache by copying and pasting the dll into %WINDIR%\assembly using Windows Explorer. Finally, navigate to http://localhost/URLRewriter/default.aspx and try the demo URLs listed.

None will actually work because there's one last thing we have to be aware of...

Finally

There's one major caveat with all this. If you want to process a request with a file extension other than .aspx such as .asp or .html, then you need to change IIS to pass all requests through to the ASP.NET ISAPI extension. Unfortunately, you will need physical access to the server to perform this, which prevents you from simply XCOPY deploying your code to an ISP.

We've added the HEAD, GET and POST verbs to all files with .* file extension (ie all files) and mapped those to the ASP.NET ISAPI extension - aspnet_isapi.dll.

The complete range of mappings, including the new .* mapping.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Richard Birkby


Member

Richard Birkby is a software engineer from London, UK, specializing in .Net. Richard has coded for many different sized companies from small venture-capital funded start-ups, to multi-national corporations (ie Microsoft). When he's not programming, he enjoys driving his sports car or eating curry (although never at the same time!). 

Richard helps run CurryPages.com and has several other covert ventures in development. Stay tuned!

Occupation: Web Developer
Location:  United Kingdom

欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 330987132 | Go:217696290 | Python:336880185 | 做人要厚道,转载请注明出处!http://www.cnblogs.com/sunshine-anycall/archive/2009/10/27/1590370.html

时间: 2024-08-01 00:46:15

Url Rewrite[转]的相关文章

EasyASP v2.2新功能介绍(2):用Easp实现伪URL Rewrite

前一篇日志介绍了EasyASP v2.2是 如何实现防sql注入的 ,看来还是有很 多人对这个年代还使用ASP报以嗤之以鼻的态度.在此还是要劝导一下,如果你 认为ASP是上个世纪的东西早就过时了,何必进来让自己难受,谢谢.EasyASP只 是以卑微的态度在给最后的ASPer们提供一种解决问题的新思路,我也相信还在 使用ASP的人对Easp有自己的评价. 不废话了,这一篇接着介绍Easp v2.2的另一个新功能:伪URL Rewrite. 1.为什么叫伪 URL Rewrite? 这个名字听起来好

IIS URL Rewrite Module防盗链规则设置详解

IIS版本:IIS 7.5 URL Rewrite组件:IIS URL Rewrite Module(http://www.iis.net/downloads/microsoft/url-rewrite) 规则定义截图: Web.config中的规则定义: <rewrite> <rules> <rule name="RequestBlockingRule1" enabled="true" stopProcessing="tru

重提URL Rewrite(4):不同级别URL Rewrite的一些细节与特点

在之前的文章里我们已经谈论了有关URL Rewrite的几个主要的方面.在本系列的最后一篇文章中,我们就来讨论一下有关不同级别URL Rewrite的一些细节与特点. 理论上说,IIS级别的URL Rewrite使用C或C++编写,比使用托管代码编写的ASP.NET级别URL Rewrite性能要高.但是我认为这方面的差距在大部分情况下可以忽略不计,这种性能几乎不可能成为性能瓶颈.因此选择何种级别的URL Rewrite一般不会由您应用程序的性能要求来决定.那么到底应该使用哪种级别的URL Re

重提URL Rewrite(3):在URL Rewrite后保持PostBack地址

在进行了URL Rewrite之后,经常会遇到的问题就是页面中PostBack的目标地址并非客户端请求的地址,而是URL Rewrite之后的地址.以上一篇文章中的重写为例: <rewriter> <rewrite url="^/User/(\d+)$" to="~/User.aspx?id=$1" processing="stop" /> <rewrite url="^/User/(\w+)$"

重提URL Rewrite(2):使用已有组件进行URL Rewrite

可能已经没有人会使用上一篇文章中的方法进行URL Rewrite了,因为提供URL Rewrite的组件早已铺天盖地了. ASP.NET级别的URL Rewrite组件的原理很简单,其实只是监听BeginRequest事件,并且根据配置来决定目标URL.在我之前接触过的项目中,发现使用URLRewriter作为URL Rewrite组件的频率非常高,我想可能是因为那是微软提供的东西吧. 如果要使用URLRewriter,首先自然就是在web.config中配置一个HttpModule: <htt

重提URL Rewrite(1):IIS与ASP.NET

之前觉得这个话题已经被谈滥了.URL Rewrite早已经被广大开发人员所接受,网上关于URL Rewrite的组件和文章也层出不穷,但是总是让我感觉意犹未尽,于是最终还是忍不住提笔写了这系列文章.这些文章不会谈论URL Rewrite的价值与意义,而只会谈论纯技术的内容.文章中也不会有详尽地实现分析,而是结合了我的经验,从应用角度来讲解这个话题.您已经知道的,您还不知道的,别处已经讲过的,或者还没有讲过的,希望这系列文章的"旧事重提"不会让您觉得沉闷,并且能让您了解ASP.NET中U

使用Microsoft Url Rewrite Module进行URL重写及Postback后保持URL的解决方案

Microsoft URL Rewrite Module 是微软推出的asp.net url重写模块,仅支持IIS7,要在IIS6上进行 url重写,可以采用一些第三方的模块,比如 urlrewriting.net.首先去下载Rewrite Module并安装.安 装完毕后,在IIS管理工具中就会出现Url Rewrite图标. 双击你需要进行URL重写的网站或者虚拟目录的URL Rewrite按钮,可以进行规则的编辑.微软的重写 模块非常强大,有很多功能,还可以自己写程序对其进行扩展.本文仅介

URL Rewrite实现jsp网站伪静态

 1.www.tuckey.org/urlrewrite/ 下载URL Rewrite JAR包 2.将jar包复制到项目WEB-INF/web.xml 下 3.在web.xml中配置URL Rewrite,代码如下: <filter> <filter-name>UrlRewriteFilter</filter-name> <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter<

IIS8如何安装和使用URL重写工具-URL Rewrite

原文:IIS8如何安装和使用URL重写工具-URL Rewrite 下载和安装URL Rewrite IIS8默认是没有安装URL重写工具的,必须要自己下载安装. 如果IIS上默认有安装Web平台安装程序,我们可以使用平台自动安装URL Rewrite重写工具,打开IIS(Internet 信息服务管理器),在管理器主页中找到管理项,打开Web平台安装程序,如下图: 在Web平台安装程序中选择产品>服务器,在列表中找到URL重写工具,点击添加后点击安装,即可自动安装好!如下图: 我们也可以手动下

为wordpress配置apache url重定向/apache url rewrite for wordpress

文章来源:http://degula.com/wordpress/200903166/wordpress-apache-rewrite.html#more-166 测试环境: windows xp/apache 2.2.11/wordpress2.7 看了很多文章都说静态url便于搜索引擎的收录,昨天晚上就将degula 的链接全都改为静态链接了,我的链接格式是:/%category%/%year%%monthnum%%post_id%/%postname%.html,效果还不错,现在是万事具备