Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace underscores in codeigniter url with dashes?

Tags:

I would like to know the simplest solution to changing the underscores of my codeigniter urls to dashes, for seo reasons.

My controllers look like:

public function request_guide() {
...Load view etc...
}

So to browse to this page I would have to go to:

www.domain.com/request_guide

But I want to be more seo friendly and use dashes instead of underscores, like so:

www.domain.com/request-guide

I am under the impression that codeigniter functions require underscores (might be wrong).

In previous projects I have simply used mod_rewrite but I believe that these actions can be performed using routes.

What is the easiest way for me to rewrite the urls replacing the underscores with dashes???

like image 243
hairynuggets Avatar asked Nov 08 '11 14:11

hairynuggets


2 Answers

It really depends on your intention. If you just want to change only one page, then devrooms' solution is the perfect one indeed:

$route['request-guide'] = "request_guide";

But if you want to make this your website's default behavior you should extend your core Router class like this (source: [Using hyphens instead of underscores in CodeIgniter])

  1. Make a new file in 'application/core' and name it 'MY_Router.php'
  2. Insert this code in it:

    <?php
    
    defined('BASEPATH') || exit('No direct script access allowed');
    
    class MY_Router extends CI_Router {
    
        function _set_request ($seg = array())
        {
            // The str_replace() below goes through all our segments
            // and replaces the hyphens with underscores making it
            // possible to use hyphens in controllers, folder names and
            // function names
            parent::_set_request(str_replace('-', '_', $seg));
        }
    
    }
    
    ?>
    

UPDATE (Oct 26, 2015): There's a better way to do this in CodeIgniter 3, as @Thomas Wood mentioned:

$route['translate_uri_dashes'] = TRUE;
like image 137
Stan Avatar answered Oct 02 '22 20:10

Stan


The routes config found in

config/routes.php

is your friend here.

A simple

$route['request-guide'] = "request_guide" ;

will do this for you.

like image 41
devrooms Avatar answered Oct 02 '22 22:10

devrooms