Php 数据库的Codeigniter.htaccess重写

Php 数据库的Codeigniter.htaccess重写,php,apache,.htaccess,codeigniter,Php,Apache,.htaccess,Codeigniter,我在使用Codeigniter时遇到困难。我试图通过将记录ID作为URL的一部分传递,从MySQL数据中获取数据 URL将被删除 localhost/site\u文件夹/page/page\u标题/2 在上面的URL中,page是控制器的名称,2是数据库中记录的主ID(可以是1到9999之间的任意数字) 我的控制器包括: public function index() { $this->load->helper('url'); $this->load->m

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

URL将被删除

localhost/site\u文件夹/page/page\u标题/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);
}
My.htaccess包含以下内容

    RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L] 
当我在地址栏中输入
localhost/site\u folder/page/page\u title/2
时,它抛出一个404。
然而,当我输入
localhost/site\u folder/page
时,它会显示默认的数据库条目,如上面
段(3,1)
的第二个值所示

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

  • 重写规则。*第/0页[PT,L]
  • 重写规则。*第页/(*)/$0[PT,L]
  • 重写规则。*第页/(?*)/$[PT,L]

您可以尝试使用CI文档中描述的
\u remap
功能

\u remap
函数(如果控制器中存在)是在任何类方法之前调用的函数,在该函数中,您可以检查发送到该函数的参数,并根据该调用检查控制器的任何方法

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


还请记住,这意味着当有人键入控制器将作为页面标题处理的随机字符串时,您应该考虑404标题的索引方法用法。

还有另一个索引“参数”问题,您需要了解此url ufo.com/page/1需要控制器“页面”和方法“1”,没有重写规则能帮你。请看这个@Kyslik:谢谢。我将URL改为,效果很好
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);
    }

}