Journal(2005) | Blog(2006) | RandomLink | WhoAmI | LiveBookmark | HomePage

<<Previous: modperl 服务器的运行阶段和句柄  >>Next: C3 method resolution order

modperl 的 PerlTransHandler 应用

Category: mod_perl   Keywords: modperl PerlTransHandler

这次讲 modperl 的PerlTransHandler,主要的作用是 url rewrite

PerlTransHandler

前面 modperl 服务器的运行阶段和句柄 中讲过 PerlTransHandler 主要用于处理 URI
如果你用过 mod_rewrite 的话,发现这个 handler 比 mod_rewrite 更实用。

假设我们为了对搜索引擎友好,将动态的 URL 地址类如

http://www.fayland.org/cgi-bin/topic.cgi?id=44
http://www.fayland.org/cgi-bin/topic.cgi?id=44&type=print
分别转为对搜索引擎更友好的静态地址如
http://www.fayland.org/topic/44
http://www.fayland.org/topic/print/44
我没用 mod_rewrite 转过,但是试验过 PerlTransHandler:
package MyApache2::RewriteTopic;

use strict;
use warnings;

use Apache2::RequestRec ();

use Apache2::Const -compile => qw(DECLINED);

sub handler {
   my $r = shift;

   # for http://www.fayland.org/topic/44
   if ($r->uri =~ m|^/topic/(\d+)/?|) {
       $r->uri("/cgi-bin/topic.cgi");
       $r->args("id=$1");
   }
   # for http://www.fayland.org/topic/print/44
   if ($r->uri =~ m|^/topic/([a-z]+)/(\d+)/?|) {
       $r->uri("/cgi-bin/topic.cgi");
       $r->args("id=$2&type=$1");
   }

   return Apache2::Const::DECLINED;
}

1;

在 perl.conf 或 httpd.conf 增加:
PerlTransHandler +MyApache2::RewriteTopic
或者是
PerlModule MyApache2::RewriteTopic
PerlTransHandler MyApache2::RewriteTopic
两者是等同的。

另外注意将 $r->uri("/cgi-bin/topic.cgi"); $r->args("id=$1"); 放到 if 里面,否则将 PerlTransHandler +MyApache2::RewriteTopic 放到某个 Location 里。
要不弄成全局,就将所有的 URI 都转向 topic.cgi 了。:)

<<Previous: modperl 服务器的运行阶段和句柄  >>Next: C3 method resolution order

Options: +Del.icio.us

Related items Created on 2005-11-23 22:24:02, Last modified on 2005-11-25 11:42:52
Copyright 2004-2005 All Rights Reserved. Powered by Eplanet && Catalyst 5.62.