【问题标题】:Codeigniter .htaccess rewriting for databaseCodeigniter .htaccess 重写数据库
【发布时间】:2014-12-07 01:02:26
【问题描述】:

我在使用 Codeigniter 时遇到了困难。我正在尝试通过将记录 ID 作为 URL 的一部分传递来从 MySQL 数据中获取数据

网址是

localhost/site_folder/page/page_title/2

在上面的 URL 中,page 是控制器的名称,2 是数据库中记录的主 ID(可以是从 1 到9999)。

我的控制器包括这个:

public function index()
{
    $this->load->helper('url');
    $this->load->model('pages_model');

    $id = $this->uri->segment(3,1);
    if (empty($id))
    {
        show_404();
    }

    $data['page'] = $this->pages_model->get_page($id);
    $this->load->view('page',$data);
}

我的 .htaccess 包含这个

    RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L] 

当我在地址栏中输入localhost/site_folder/page/page_title/2 时,它会抛出 404。
然而,当我输入localhost/site_folder/page 时,它会显示默认数据库条目,如上面segment(3,1) 的第二个值所示。

那么,我应该如何更改 .htaccess 文件以进行可行的重写?
我尝试了以下方法,但没有一个对我有用:

  • RewriteRule .* page/$0 [PT,L]
  • RewriteRule .* page/(*.)/$0 [PT,L]
  • RewriteRule .* page/(?*.)/$ [PT,L]

【问题讨论】:

  • 又一个索引“参数”问题,你需要明白这个 url ufo.com/page/1 想要控制器“页面”和方法“1”,没有重写规则会帮助你看到这个question/answer
  • @Kyslik:谢谢。我将 URL 更改为 localhost/ci/page/index/1,它工作正常

标签: php apache .htaccess codeigniter


【解决方案1】:

您可以尝试使用 CI 文档 https://ellislab.com/codeigniter/user-guide/general/controllers.html 中描述的 _remap 函数

_remap 函数如果存在于控制器中,是在任何类方法之前调用的函数,在此函数中,您可以检查发送给函数的参数,并根据此调用控制器的任何方法。

对于您的示例,因为我假设 page_title 是动态的,您可以设置一个正则表达式来检查它,或者在下面的示例中检查该方法是否不存在,然后将其视为页面标题(这意味着您必须是确保这个控制器中不能有同名的页面标题和方法名)

public function _remap($method, $params = array())
{
    if (!method_exists($this, $method))
    {   
        // assume this is a page_title and run the index method

        $this->index($method, $params);     
    }
    else {
        // means that method exists then run that method
        $this->$method( $params);
    }

}

还请记住,这意味着当有人只是键入控制器将视为 page_title 的随机字符串时,您应该考虑 404 标头的索引方法使用。

【讨论】:

    猜你喜欢
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多