2014-12-07 99 views
0

我在使用Codeigniter时遇到困难。我试图通过将记录ID作为URL的一部分,以获得从MySQL数据数据Codeigniter .htaccess数据库重写

的网址是要

本地主机/ site_folder /页/ PAGE_TITLE/2

在上面的URL中,页面是控制器的名称,而是数据库中记录的主要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文件以进行可行的重写呢?
我曾尝试以下,但没有为我工作:。

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

另一个索引“参数”的问题,你需要明白,这个网址ufo.com/page/1希望控制器“页面”和方法“1”,没有重写规则会帮助你看到这个[问题/回答](http://stackoverflow.com/a/27220596/1564365) – Kyslik 2014-12-07 16:50:56

+1

@Kyslik:谢谢。我将URL更改为http:// localhost/ci/page/index/1,并且工作正常 – 2014-12-07 20:54:37

回答

0

您的CI文件https://ellislab.com/codeigniter/user-guide/general/controllers.html

的描述可以尝试使用_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); 
    } 

} 

还记得那就是说,你应该考虑在404头的索引方法使用时,有人只需要输入随机字符串,控制器将视为page_title。