使用Apache mod_rewrite Kohana 2.3.4将下划线转换为破折号

时间:2014-09-24 10:30:32

标签: kohana

如何在Kohana 2.3.4中使用Apache mod_rewrite将下划线转换为破折号

假设我有www.site.com/purchase_item

我希望它是

www.site.com/purchase-item

从SEO的角度来看,后者是首选的

1 个答案:

答案 0 :(得分:0)

有很多方法可以解决这个问题,最简单的方法可能就是使用mod_rewrite规则。您可以使用两个重写规则执行您想要执行的所有操作:

  1. 将带有下划线的所有请求重定向到破折号
  2. 使用破折号将所有请求重写为下划线,以便后端(kohana)轻松处理。
  3. 我没有对此进行测试,但我认为它应该有效:

    # redirect all requests with underscore to dash (this will do three dashes at a time, hopefully results in only one redirect for the client)
    RewriteCond %{REQUEST_URI} ([^_]*)_([^_]*)
    RewriteCond %1-%3 ([^_]*)(_([^_]*))?
    RewriteCond %1-%3 ([^_]*)(_([^_]*))?
    RewriteCond %1-%3 ([^_]*)-*$
    RewriteRule .* %1 [L,R=301,QSA]
    
    # rewrite all requests with dash back to underscore
    RewriteCond %{REQUEST_URI} ([^-]*)-([^-]*)
    RewriteCond %1_%3 ([^-]*)(-([^-]*))?
    RewriteCond %1_%3 ([^-]*)(-([^-]*))?
    RewriteCond %1_%3 ([^-]*)_*$
    RewriteRule .* %1 [L]