简体   繁体   中英

Codeigniter .htaccess rewriting for database

I am having difficulties with Codeigniter. I am trying to get data from a MySQL data by passing the record ID as part of the URL

The URL is to be

localhost/site_folder/page/page_title/2

In the above URL, page is the name of the controller and 2 is the primary ID of the record in the database (this could be any number from 1 to 9999).

My controller includes this:

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 contains this

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

When I enter localhost/site_folder/page/page_title/2 into the address bar, it throws a 404.
Yet, when I enter localhost/site_folder/page it shows the default database entry as shown in the second value of segment(3,1) above.

So, how should I change the .htaccess file for a workable rewrite?
I have tried the following, but none worked for me:

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

You can try using the _remap function as described in the CI documentation https://ellislab.com/codeigniter/user-guide/general/controllers.html

The _remap function if exists in a controller is the a function that is called before any class method, and in this function you can check params sent to the function and according to this call any method of the controller.

For your example as i assume that page_title is dynamic you can either set a regular expression to check it or as in the following example check if the method does not exists then treat it as a page title (this means that you must be sure there can not be a page title and a method name in this controller with the same name)

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);
    }

}

Also remember that means that you should take into consideration in the index method usage of 404 header when someone just type random string that the controller will treat as a page_title.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM