Url Rewrite 重写

前几天看到园子里一篇关于 Url 重写的文章《获取ISAPI_Rewrite重写后的URL》 , URL-Rewrite 这项技术早已不是一项新技术了,这个话题也已经被不少人讨论过屡次。搜索一下URL-Rewrite能够找到不少URL-Rewrite方面的文章和组 件,本身之前也屡次接触过这个东东,也来讲说吧。 ScottGu 有一篇很是经典的 URL-Rewrite Bloghtml

Tip/Trick: Url Rewriting with ASP.NET  http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspxlinux

 

为何要进行URL-Rewrite
ScottGu的blog中给出了两个重要的缘由:
1.保证WebApplication在进行结构调整,移动页面位置时,用户收藏的URL不会所以而成为死链。
2. SEO优化。
摘引自ScottGu Blog 的原文ios

---------------------------------------------------------------------------
Why does URL mapping and rewriting matter?
The most common scenarios where developers want greater flexibility with URLs are:
1) Handling cases where you want to restructure the pages within your web application,
and you want to ensure that people who have bookmarked old URLs dont break when you move pages around.
Url-rewriting enables you to transparently forward requests to the new page location without breaking browsers. 2) Improving the search relevancy of pages on your site with search engines like Google, Yahoo and Live.
Specifically, URL Rewriting can often make it easier to embed common keywords into the URLs of the pages on your sites,
which can often increase the chance of someone clicking your link. Moving from using querystring arguments to instead
use fully qualified URLs can also in some cases increase your priority in search engine results.
Using techniques that force referring links to use the same case and URL entrypoint
(for example: weblogs.asp.net/scottgu instead of weblogs.asp.net/scottgu/default.aspx) can
also avoid diluting your pagerank across multiple URLs, and increase your search results. In a world where search engines increasingly drive traffic to sites, extracting
any little improvement in your page ranking can yield very good ROI to your business.
Increasingly this is driving developers to use URL-Rewriting and other SEO (search engine optimization) techniques to
optimize sites (note that SEO is a fast moving space, and the recommendations for increasing your search relevancy evolve monthly).
For a list of some good search engine optimization suggestions, Id recommend reading the SSW Rules to Better Google Rankings, as
well as MarketPositions article on how URLs can affect top search engine ranking. ---------------------------------------------------------------------------

 第一点缘由中所描述的场景,在Web站点改版中常常碰到。Web站点改版常常会调整一些页面的位置,QueryString中参数的结构等等。极可能使原 来用户在收藏夹中收藏的连接成为死链。在这种场景下URL-Rewrite像是软件架构技术中的一个中间层的概念,URL-Rewrite对外公开的 URL是被重写过的,这个URL被用户收藏,不会变,当Web站点调整,内部Page的位置改变了,使得内部实际的URL地址也改变了,这时修改内部的重 写规则,让原来对外公开的URL重写到新的内部URL上。从而保证了对外URL不变,其实对内已经完成了页面位置的调整。虽然URL-Rewrite能够 作到防止死链的产生,可是大多数站点在改版或调整时,不会使用URL-Rewrite来防止死链的产生,通常会直接修改404 The page cannot be found 页面,把404出错页面改为一个更加友好的提示页面,而且会在几秒钟以后跳转到网站首页。web


  第二点缘由是SEO了,若是您的站点是个内部OA ERP CRM这种站点,只须要本身内部人员来访问。其实彻底能够不用作SEO,由于这种站点根本不须要搜索引擎来收录,也不须要别人经过搜索引擎找到这个站点, 因此这种站点彻底没有必要进行SEO优化。若是您的站点是个商业站点,新闻站点,娱乐站点,越多人访问越好的站点,SEO优化是很是重要,此时经过 URL-Rewrite进行SEO优化也就很是必要了。随着搜索引擎逐渐成为人们查找信息,索取资源的首选工具,搜索引擎对一个站点的影响也就越来越大, 下面是 zhangsichu.com 9-1~9-10 这段时间内的第三方来路数据统计。正则表达式

11_142504_74v0urlRewrite

路统计是经过记录httpheader中的Referer,来得知用户在浏览这个页面以前所在的那个页面。从而得出用户是经过那个页面到达这个页面的。
在 266个独立IP中,有200个IP是来自搜索引擎的。也就是说,用户先经过搜索引擎的搜索结果,而后来到zhangsichu.com的用户有200 个。占到了75.2%。一大半的人是经过搜索来的。充分说明了SEO对站点的重要,在这种状况下,就必须作URL-Rewrite进行SEO优化了。服务器

 
若是您的站点既不须要考虑URL兼容防止死链问题,也不须要进行SEO优化,就彻底没有必要进行URL-Rewrite。URL-Rewrite是一个对性能有害的处理过程。cookie


经常使用的URL-Rewrite方案
URL-Rewrite既能够发生在Web服务器(IIS/Apache)一级,也能够发生在Web应用程序一级(Asp.Net/Jsp/PHP/…)。架构

 
1.Web应用程序级别的URL-Rewrite
  在Web应用程序级别的URL-Rewrite。有三个比较著名的现成组件。
  1) 微软提供的 URL-Rewrite http://msdn2.microsoft.com/zh-cn/library/ms972974.aspx
  2) Open Source的 UrlRewriter.NET http://urlrewriter.net/
  3) UrlRewriting http://www.urlrewriting.net/en/Download.aspxapp

这种组件内部核心的工做原理: 都是在本身的Web Application的web.config中添加httpModule。用这个httpModule来处理重写。(其实也可继承 System.Web.HttpApplication,在Application_BeginRequest中插入一个本身的方法处理重写)asp.net


其中核心的处理代码,下面的代码摘引自UrlRewriter.NET组件。
  1)从IHttpModule继承获得一个本身的HttpModule,这个HttpModule须要在web.config中配置,说明全部的请求都要通过这个HttpModule。

public sealed class RewriterHttpModule : IHttpModule
  {
    /// <summary>
    /// Initialises the module.
    /// </summary>
    /// <param name="context">The application context.</param>
    void IHttpModule.Init(HttpApplication context)
    {
      context.BeginRequest += new EventHandler(BeginRequest);
    }
…
private void BeginRequest(object sender, EventArgs e)
    {
      // Add our PoweredBy header
      HttpContext.Current.Response.AddHeader(Constants.HeaderXPoweredBy, Configuration.XPoweredBy);
 
      _rewriter.Rewrite();
    }
}

2)读取重写规则,判断是否须要重写,肯定如何重写,进行重写。

public void Rewrite()
    {
      string originalUrl = ContextFacade.GetRawUrl().Replace("+", " ");
      RawUrl = originalUrl;
 
      // Create the context
      RewriteContext context = new RewriteContext(this, originalUrl,
        ContextFacade.GetHttpMethod(), ContextFacade.MapPath,
        ContextFacade.GetServerVariables(), ContextFacade.GetHeaders(), ContextFacade.GetCookies());
 
      // Process each rule.
      ProcessRules(context);
 
      // Append any headers defined.
      AppendHeaders(context);
 
      // Append any cookies defined.
      AppendCookies(context);
 
      // Rewrite the path if the location has changed.
      ContextFacade.SetStatusCode((int)context.StatusCode);
      if ((context.Location != originalUrl) && ((int)context.StatusCode < 400))
      {
        if ((int)context.StatusCode < 300)
        {
          // Successful status if less than 300
          _configuration.Logger.Info(MessageProvider.FormatString(Message.RewritingXtoY,
            ContextFacade.GetRawUrl(), context.Location));
 
          // Verify that the url exists on this server.
          HandleDefaultDocument(context);// VerifyResultExists(context);
 
          ContextFacade.RewritePath(context.Location);
        }
        else
        {
          // Redirection
          _configuration.Logger.Info(MessageProvider.FormatString(Message.RedirectingXtoY,
            ContextFacade.GetRawUrl(), context.Location));
 
          ContextFacade.SetRedirectLocation(context.Location);
        }
      }
      else if ((int)context.StatusCode >= 400)
      {
        HandleError(context);
      }
      else if (HandleDefaultDocument(context))
      {
        ContextFacade.RewritePath(context.Location);
      }
 
      // Sets the context items.
      SetContextItems(context);
    }

这种重写是ASP.NET Pipeline级别的重写,能够重写一切Asp.net接管的请求。

11_144458_zwo3urlRewrite1

在这里对/Pd/Book.aspx的请求被重写到了 /Pd.aspx?Cg=books.
Web应用程序级别的URL- Rewrite只能重写Web应用程序接管的请求。它没有办法处理.js .jpg的重写。缘由是这些请求到达IIS后,IIS根本就没有把这些请求分发到Asp.Net,因此这些请求就不会发生重写的处理和操做。在IIS中可 以配置,对哪些后缀的请求是被IIS分发到Asp.Net的。

 

11_142520_fc5iurlRewrite2

 

若是您必定要在Asp.Net级别对.js的请求进行重写,能够在这里指定.js的请求由Asp.Net接管,可是这时您须要本身处理.js的Response。Web服务器级别的URL-Rewrite能够比较好的解决这方面的问题吧。

2. Web服务器级别的URL-Rewrite

 


Apache服务器
Apache服务器原生支持了URL-Rewrite。在config中打开LoadModule rewrite_module modules/mod_rewrite.so 而后配置重写的正则表达式。例如:


摘引自Apache2.2中文参考手册 中文手册 Apache-UrlRewrite

---------------------------------------------
描述:
这个规则的目的是强制使用特定的主机名以代替其余名字。好比,你想强制使用www.example.com代替example.com,就能够在如下方案的基础上进行修改:
解决方案:
对运行在非80端口的站点
 
RewriteCond %{HTTP_HOST} !^fully\.qualified\.domain\.name [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{SERVER_PORT} !^80$
RewriteRule ^/(.*) http://fully.qualified.domain.name:%{SERVER_PORT}/$1 [L,R]
 
对运行在80端口的站点
 
RewriteCond %{HTTP_HOST} !^fully\.qualified\.domain\.name [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/(.*) http://fully.qualified.domain.name/$1 [L,R]
---------------------------------------------------------------------------
相关文章
相关标签/搜索