如何使用Kohana生成SEO友好的URL


How to generate SEO friendly URL using Kohana

目前我的url看起来像mysite.com/product/display/10,意思是domain/controller/function/id,为了SEO友好起见,我想添加product title,它将像product name something

根据我对SEO的基本知识,我所知道的是,对于SEO友好的url应该像mysite.com/product/display/product-name-something/id

Kohana 2.x中有什么有效的方法可以做到这一点吗?如果在Kohana中无法做到,请在PHP中建议使用.htaccess文件或不使用.htaccess的有效且更好的方法。

您应该使用ROUTES来声明友好的URL。在config/routes.php文件中,如下所示:

$config['route'] = 'class/method';

在您的情况下:

$config['product/display/([a-zA-Z0-9-]+)/([0-9]+)'] = 'product/display/$2';

更多信息:http://docs.kohanaphp.com/general/routing

要更改字符串,请使用以下方法:

function toUrl($string) {
        // small fonts
        $sText = strtolower($string);
        // change spaces to -
        $sText = str_replace(' ', '-', $sText);
        // delete all other characters to -
        $sText = preg_replace('|[^0-9a-z'-'/+]|', '', $sText);
        // delete too much - if near
        $sText = preg_replace('/['-]+/', '-', $sText);
        // trim -
        $sText = trim($sText, '-');
        return $sText;
}