I have completed the well known 'news' toutorial included in CI documentation. sometimes double 'news/' segment occurs in my linking strings like this: '/codeig/news/news/entry' and sometimes after reloading page everything works right. i should mention i have got rid of 'index.php' segment following another popular tutorial. what is wrong with my code ?
this is my routing:
$route['news/create'] = 'news/create';
$route['news/update/(:any)'] = 'news/update/$1';
$route['news/delete/(:any)'] = 'news/delete/$1';
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['welcome'] = 'welcome';
$route['auth/(:any)'] = 'auth/$1';
$route['auth'] = 'auth';
$route['activate/:num/:any'] = "/auth/activate/$1/$2";
$route['reset_password/:num/:any'] = "/auth/reset_password/$1/$2";
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'news';
views/news/index.php file:
<?php foreach ($news as $news_item): ?>
<h2><?php echo $news_item['title'] ?></h2>
<div id="main">
<?php echo $news_item['text'] ?>
</div>
<p><a href="news/<?php echo $news_item['slug'] ?>">View article</a></p>
<?php endforeach ?>
view method (news controller)
public function view($slug)
{
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
In HTML, if the current URL is something like this:
http://example.com/news/
And you have links like this:
<a href="news/article-slug">Link</a>
After clicking the link, your URL will end up being:
http://example.com/news/news/article-slug
If you clicked it again, you'd have:
http://example.com/news/news/article-slug/news/article-slug
Note: This isn't exactly right, the relativity of the path does depend on whether or not there's a trailing slash /
in the current URL and/or your links.
href="news/something"
is a relative URL, relative to the current page. You want to use either absolute or rooted URLs:
<a href="http://example.com/mysite/news/article-slug">Link</a>
<a href="/news/article-slug">Link</a>
Use any of the following Codeigniter functions to make absolute URLs easier:
anchor()
(makes the whole link for you)site_url()
(returns your absolute base URL)base_url()
(same as above)<?php echo anchor('news/'.$news_item['slug'], 'Link Text'); ?>
<a href="<?php echo base_url('news/'.$news_item['slug']); ?>">Link Text</a>
So just to clarify, this has nothing to do with your routing - it's purely a problem with relative links in your HTML.