0

我想为存储在数据库中的产品创建对 SEO 更友好的 URL。

如何从 URL 中获取 ProductName?

例如:

http://domain.com/ProductName

其中 ProductName 不是控制器。我需要从控制器验证 ProductName 并显示它。

4

4 回答 4

5

我个人会创建一个名为 products 的控制器,它接受一个参数以从数据库中查找产品:

class Products extends CI_Controller
{
    public function index($productname)
    {
        $data['product'] = $this->db->get_where('products', array('urlname' => $product))->row_array();
        // other functionality here and view loading
    }
}

然后为这个场景添加路由(config/routes.php):

$route['other/routes/first'] = "their/correct/controller/$1";
$route['/(:any)'] = "/products/index/$1";

自从我使用 CI 以来已经有一段时间了,但这应该可以帮助您指出我希望的正确方向。

于 2012-11-30T08:47:13.870 回答
2

您可以在 routes.php 中添加路由规则 将请求重定向到 Product 控制器

$route['(:any)'] = "product/$1";

在您的产品控制器中,从 URI 段获取产品名称

$product_name = $this->uri->segment(2);
于 2012-11-30T08:47:45.170 回答
0

您可以使用URI 路由(路由规则)

路由规则在您的 application/config/routes.php 文件中定义。在其中您将看到一个名为 $route 的数组,它允许您指定自己的路由条件。可以使用通配符或正则表达式指定路由

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

此示例将导致:http://www.example.com/MyProductName/加载将名称作为参数的产品类。

于 2012-11-30T08:51:48.960 回答
-3

您可以利用 CI 路由来实现这一点

编辑 Application/config/routes.php

$route['/(:any)'] = "/products/index/$1";
于 2012-11-30T09:06:59.937 回答