【问题标题】:Hyphens in URLs with Kohana PHP Framework使用 Kohana PHP 框架的 URL 中的连字符
【发布时间】:2011-04-18 18:44:44
【问题描述】:

这是一个 Apache .htaccess 问题。

在 Kohana PHP 框架(我在 3.1)中,它们似乎不支持控制器或操作的 URL 中的连字符,这是域之后的前 2 个 URL 参数,如下所示:

http://example.com/controller/action

http://example.com/blogs/edit-article

有没有一种方法可以让我的 .htaccess 文件从控制器和操作插槽中去除连字符(破折号),但不能从其他插槽中去除?这是我当前的 .htaccess 文件:

Options All +FollowSymLinks -Indexes -Multiviews

# Turn on URL rewriting
RewriteEngine On

# Installation directory
RewriteBase /

# Protect hidden files from being viewed
<Files .*>
    Order Deny,Allow
    Deny From All
</Files>

RewriteRule ^assets/(.*)$   application/views/assets/$1

RewriteCond %{REQUEST_FILENAME} !/application/views/assets/.*

# Protect application and system files from being viewed
RewriteRule ^(?:application|modules|system)\b.* index.php/$0 [L]

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT]

【问题讨论】:

标签: php .htaccess frameworks apache2 kohana


【解决方案1】:

在我的项目的 Kohana 3.1 的 boostrap.php 中,我必须在默认路由上方添加:

Route::set(
    'custom',
    function($uri) {
        $uri = rtrim($uri, '/');
        $asParts = @ explode('/',$uri);
        $controller = @ $asParts[0];
        $action = @ $asParts[1];
        $param1 = @ $asParts[2];
        $param2 = @ $asParts[3];
        $param3 = @ $asParts[4];
        $controller = str_replace('-','_',$controller);
        $action = str_replace('-','_',$action);
        $controller = (empty($controller)) ? 'home' : $controller;
        $action = (empty($action)) ? 'index' : $action;
        return array(
            'controller' => $controller,
            'action' => $action,
            'param1' => $param1,
            'param2' => $param2,
            'param3' => $param3
        );
    }
);

这让我可以做以下事情:

  • 操作中的破折号变成了控制器类中的函数,并带有下划线。所以,'add-new' 变成了 'action_add_new()'。
  • 控制器中的破折号成为子文件夹,因为控制器在 kohana 中自然下划线表示子文件夹。因此,由于控制器上面的 str_replace() 函数,如果我有一个控制器“test1-test2”,Kohana 会寻找一个控制器文件夹“test1”,然后是一个控制器文件“test2.php”。但问题是,您的 test2.php 需要以 'class Controller_Test1_Test2 extends Controller {' 开头。
  • 然后我还可以在 URL 之后传递 3 个对 SEO 友好的参数,而无需使用更丑陋的 ?p1=blah&p2=blah&p3=blah 查询参数技术。这是explained more here

【讨论】:

    猜你喜欢
    • 2017-05-14
    • 2011-11-11
    • 1970-01-01
    • 2012-09-02
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多