简体   繁体   English

使用CodeIgniter重写网址

[英]Rewrite the url using CodeIgniter

I read a lot of forum topics but I did not found any answer which meets my needs. 我阅读了很多论坛主题,但没有找到符合我需求的答案。

I am running a blog system and my current urls for each article look like: www.example.com/controller/method/id . 我正在运行一个博客系统,每篇文章的当前URL如下: www.example.com/controller/method/id However, for each article I have a title stored in a database, and would like to use that title in the url, so it would look like this: www.example.com/title 但是,对于每篇文章,我都有一个标题存储在数据库中,并且想在URL中使用该标题,因此它看起来像这样: www.example.com/title

Hello there you are asking for a whole lot of code and you did not do any research yourself. 您好,您需要大量的代码,您自己没有做任何研究。

The best way is to use id with your title: http://www.example.com/id/long-title it is much better than using only title, because: 最好的方法是在标题中使用id: http://www.example.com/id/long-title : http://www.example.com/id/long-title它比仅使用标题好得多,因为:

  1. same title can occur more than once (creates problem that can be avoided) 同一标题可能多次出现(造成可以避免的问题)
  2. slow loading/searching due querying by slug instead of ID (slow performance) 加载/搜索速度慢,原因是通过Slug而不是ID进行查询(性能低下)
  3. user needs to remember whole title (with id+title; user can copy partially broken url www.example.com/234593/this-title-is-) / opinion based 用户需要记住整个标题(带有id + title;用户可以复制部分破损的网址www.example.com/234593/this-title-is-)/基于意见

In order to make my proposal work you need to: 为了使我的建议生效,您需要:

set up routes (application/config/routes.php) 设置路由(application / config / routes.php)

//leave two CodeIgniter's routes on top
$route['default_controller'] = "welcome";
$route['404_override'] = '';

//leave this two routes in this order + make them LAST routes
$route['(:num)'] = 'blog/post/$1'; //if only id is in url
$route['(:num)/(:any)'] = 'blog/post/$1/$2'; //if id and title is in url

set up controller (application/controllers/blog.php) 设置控制器(application / controllers / blog.php)

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Blog extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        //load models helpers etc if not autoloaded
        $this->load->helper('url');

    }

    public function index()
    {
        echo 'should throw 404 or redirect home because id was not provided';

    }

    public function post($id = null, $title = '') 
    {
        if (!$this->validId( $id )) redirect(); //redirect somewhere because id of post is invalid search/404/home...
        if (empty(trim($title))) {
            redirect(base_url().$id.'/'.$this->getTitle($id), 'location', 301); //redirect to same page search engines friendly (301 header)
        }

        //display what you need

        echo 'params; id: ' . $id . ' title: ' . $title;

    }

    private function validId($id) 
    {
        if (is_numeric($id))
            return true; //use database to check validity in this case every id is valid
    }

    private function getTitle() 
    {
        //id should be good to use at this point
        //get title using database
        return $this->seoUrl('How you react of crying babies will determine their future.');    //made up title 
    }

    private function seoUrl($string) 
    {
        //source: http://stackoverflow.com/a/11330527/1564365
        //Lower case everything
        $string = strtolower($string);
        //Make alphanumeric (removes all other characters)
        $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
        //Clean up multiple dashes or whitespaces
        $string = preg_replace("/[\s-]+/", " ", $string);
        //Convert whitespaces and underscore to dash
        $string = preg_replace("/[\s_]/", "-", $string);
        return $string;
    }
}

/* End of file blog.php */
/* Location: ./application/controllers/blog.php */

thats it, now create yourself model that can validate ID, grab title... 就是这样,现在创建自己的模型来验证ID,获取标题...

sample code (of model): 示例代码(模型):

public function isInDb($table, $where = array())
{
    $q = $this->db->get_where($table, $where);
    return ($q->num_rows() > 0) ? true : false; //returns either true or false, pretty straight forward
}

public function getColumn(){}

Now you use (generate) url www.example.com/1 (this will redirect with 301 header to /1/title ) or you can use (generate) www.example.com/1/title link, however if you generate url like: /1/fake-title (title is invalid for id 1 it will not redirect to the correct one) 现在,您使用(生成)URL www.example.com/1 (它将使用301标头重定向到/1/title ),或者您可以使用(生成) www.example.com/1/title链接,但是,如果您生成url例如: /1/fake-title (标题对于ID 1无效,它将不会重定向到正确的标题)

This solution is SEO friendly. 该解决方案是SEO友好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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