简体   繁体   中英

Seo-friendly url in CodeIgniter

I've created a filter method for filtering the products list. This is my URL:

localhost/myshop/products/filter?category=shirts&color=blue&page=1

But I want to show this way:

localhost/myshop/products/shirts/blue/1

How can I achieve it?

Assuming that Products::filter() is responsible for handling the request, you can rewrite the method to accept parameters in its signature. So, if the current logic is something like this:

class Products extends CI_Controller
{
    public function filter()
    {
        // Retrieve data from GET params
        $page     = $this->input->get('page');
        $color    = $this->input->get('color');
        $category = $this->input->get('category');
    
        // Do the filtering with $category, $color and $page...
    }
}

You can simply refactor it to accept parameters through URL segments:

public function filter($category, $color, $page)
{        
    // Do the filtering with $category, $color and $page...
}

With this in place, your current URL is:

localhost/myshop/products/filter/shirts/blue/1

We need to get rid of that extra filter/ and we're done, right? Quoting from the docs :

Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method. The segments in a URI normally follow this pattern:

example.com/class/method/param1/param2

In some instances, however, you may want to remap this relationship so that a different class/method can be called instead of the one corresponding to the URL.

OK, so we need to remap the current route. You have a few options:

  • First, is to update your application/config/routes.php file with a new entry:

     $route['products/(:any)'] = 'products/filter/$1';

    It says that if a URL starts with products/ , remap it to the filter method of products class.

    Here you can use wildcards and regex patterns to be even more precise about the type of parameters your method accepts.

  • Another option is that you might want to implement a _remap() method in your controller in order to do the route remapping for you.

in routes.php file, you can write following line

    $route['products/(:any)/(:any)/(:num)'] = 'products/filter/$1/$2/$3';

and function will be like following

    public function filter($category, $color, $page)
    {        
        echo $category.'<br>';
        echo $color.'<br>';         
        echo $page.'<br>';
    }

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