简体   繁体   中英

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

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:

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

In order to make my proposal work you need to:

set up routes (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)

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

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)

This solution is SEO friendly.

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