php - CodeIgniter 中的 Seo 友好 url

标签 php codeigniter url routes seo

我创建了一个用于过滤产品列表的过滤方法。这是我的网址:

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

但是我想这样展示:

localhost/myshop/products/shirts/blue/1

我怎样才能实现它?

最佳答案

假设 Products::filter() 负责处理请求,您可以重写该方法以在其签名中接受参数。所以,如果当前的逻辑是这样的:

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...
    }
}

您可以简单地重构它以通过 URL 段接受参数:

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

有了这个,您当前的 URL 是:

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

我们需要去掉那个额外的 filter/ 就完成了,对吧?引用自 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.

好的,所以我们需要重新映射当前路线。您有几个选择:

  • 首先,是用新条目更新您的 application/config/routes.php 文件:

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

    它表示如果 URL 以 products/ 开头,则将其重新映射到 products 类的 filter 方法。

    在这里您可以使用通配符和正则表达式模式来更加精确地确定您的方法接受的参数类型。

  • 另一种选择是您可能希望实现 _remap() Controller 中的方法,以便为您进行路由重新映射。

关于php - CodeIgniter 中的 Seo 友好 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40866690/

相关文章:

php - 仅从 php 中的 url 获取文件名,而 url 中不存在任何变量值

php - Google 报告了一些实际上并不存在的 404 错误。这是否表明我的网站被黑了?

php - 用户在调用 mysqli_real_connect 时收到来自 PHP 脚本的截断消息(最多 19109 个字符)

javascript - html提交表单ajax响应

php - 需要帮助来开发具有 2 种语言的网站英语和法语

php - 使用 Codeigniter 获取登录用户的所有消息以及每条消息的所有答案

php - 从数据库中删除 php 数组中不存在的数据

java - 在 java 中获取 URL 参数并从该 URL 中提取特定文本

javascript - 使用 html 和 php 生成密码

php - 我可以在不使用 S3 API 的情况下从我的 Amazon S3 帐户下载文件吗?