Relative URLs with CodeIgniter

Using CodeIgniter pretty URLs while having relative paths in the generated HTML.

How it works

This hook updates base_url config item depending on the current URL. For


base_url will be set to




will generate


Enable hooks


$config['enable_hooks'] = TRUE;

Declare hook


// set base url
$hook['post_controller_constructor'][] = array(
	'class' => '',
	'function' => 'rewrite_base_url',
	'filename' => 'uri.php',
	'filepath' => 'hooks'

The hook


<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function rewrite_base_url()
	$n = count(explode('/', uri_string())) - 2;
	$str = '';
	for ($i=0; $i < $n; $i++)
		$str .= '../';
	$CI =& get_instance();
	$CI->config->set_item('base_url', $str);
/* End of file uri.php */
/* Location: ./system/application/hools/uri.php */



"Relative URLs with CodeIgniter" Unfortunately this doesn't work for me. It's always putting "index.php" instead of "../", so relative address is ruined. Maybe you have any suggestion why is this happening? I've tryied with typical url/controller/function/params/, also with different changed routes and it's all wrong. Have any idea why?
Sep 4, 2009
* Detect relative url
* @param string $ex
* @return string
function relative_path($ex = './')
$uri = uri_string();
$url = '';
for($i = 1; $i < substr_count($uri, '/'); $i++)
$url.= '../';

return $ex . $url;
Dec 9, 2010
hello thanks for share this relative urls that help me alot, but i have problem, i use redirect in my php but it just show Refresh: 0;url=../../ is there any method to fix redirect ?
Jul 24, 2013
I know a little bit about relative path. Suppose, I have a project on codeigniter. There are 4 controller such as with function name:

1. Admin->index,profile,add_student,edit_marks,make_admin,
2. Teacher->index,add_marks,update_marks
3. Student->index,view_teacher,view_result
4. Guest->index,view_Student, view_marks,view_result
From these, How can I use them as relative path ?Remind it,some times I go one controller to another controller, such as profile,view_marks is a common function for all, so every one access it.

For images or file can I use relative path ? Then,Suppose I have a image at root folder as ->root_folder/template/images/a.png. How can I use it as relative path ?

Really, I need the core knowledge of relative path with application in codeigniter.

This question is available at
Jun 19, 2014
Please How can i add www. to the name of my website using codeigniter eg:
Aug 6, 2014