45tr 发表于 2015-8-5 12:06:58

apache mod_rewrite 模块使用的几个例子

apache mod_rewrite 模块使用的几个例子
  
当我们在网上冲浪的时候,指引我们前进的路标就是URL。对网站开发者来讲一个合理设计的URL对用户、合作网站的友情连接,链接地址引用以及搜索引擎的
抓取都非常重要。大家知道URL一般有2种类型:1、静态URL2、动态URL
。静态URL的设计取决于网站目录的设计,可以说是和URL对应的文件是影射关系,因此静态URL的设计比较简单。但现在动态URL占到了全部URL的
90%以上(参见微软研究院的搜索报告),动态URL的参数少则2三个,多则10几个,这样非常不利于网站用户的“阅读”。如何把复杂难记动态URL整理
成易于用户和搜索引擎的显示方式就显得非常重要了。

    本文介绍 apache mod_rewrite 实现 url rewrite 的几种方式:

    假设:有如下需要 url rewrite的 url:   


http://www.domolo.com/tianchunfeng
http://blog.iyunv.com/accesine960
http://360.yahoo.com/tcf960

http://www.donews.net/accesine  你想把上面这些页面通过一个统一的的方式来访问:

比如是:

http://www.domolo.com/tianchunfeng   
------>
http://www.domolo.com/tianchunfeng
http://blog.iyunv.com/accesine960   
------>
http://www.domolo.com/accesine960
http://360.yahoo.com/tcf960         
------>
http://www.domolo.com/tcf960

http://www.donews.net/accesine      
------>
http://www.domolo.com/accesine  那么可以用如下方式实现:

1、建立一个 影射文件:domolo.map 并把它放在:/APACHE_HOME/apache/conf目录下:

    tianchunfeng
http://www.domolo.com/tianchunfeng

    accesine960
http://www.domolo.com/accesine960

    tcf960
http://www.domolo.com/tcf960

    accesine
http://www.domolo.com/accesine
  2、RewriteMap fishmap txt:/APACHE_HOME/apache/conf/domolo.map
  3、RewriteEngine On

RewriteRule ^/myhomepage/(.*) ${domolo:$1}


  这样当用户访问: http://domolo/myhomepage/tianchunfeng, 的时候实际转向到
http://www.domolo.com/tianchunfeng。
  这个规则挺方便的吧。

在我们访问Web页面的时候偶尔会碰到404错误,就是页面无法访问,这个也可以通过 url Rewrite来实现:

RewriteRule ^/myhomepage/(.*) ${domolo:$1|http://www.domolo.com/}
上面的例子是1对1的影射url rewrite,更复杂的可以用以下的方式来实现,比如:
#!/usr/bin/perl
    $| = 1; # Turn off buffering
    while () {
            s/-/_/g; # Replace - with _ globally
            print $_;
    }
上面的例子是把url中所有的符号“-”换成:“_”

我们把上面的perl保存成:dash3score.pl ,并做如下配置:
RewriteMap dash2score prg:/APACHE_HOME/conf/dash2score.pl
RewriteEngine On
RewriteRule (.*-.*) ${dash2score:$1}

一个更复杂的例子是把影射关系存储在数据库中,不妨看看下面的例子(配置省略):

    #!/usr/bin/perl
    use DBI;
    $|=1;
    my $dbh = DBI->connect('DBI:mysql:wordpress:dbserver','username', 'password');
    my $sth = $dbh->prepare("SELECT ID FROM wp_postsWHERE post_name = ?");
    my $ID;

    # Rewrite permalink style links to article IDs
    while (my $post_name = ) {
      chomp $post_name;
      $sth->execute($post_name);
      $sth->bind_columns(\$ID);
      $sth->fetch;

      print "/domolo/index.php?p=$ID\n";
    }
相关链接:
多么乐
ApacheCookbook
田春峰
20050515


页: [1]
查看完整版本: apache mod_rewrite 模块使用的几个例子