Php – How to link assets(images,stylesheet etc) in Views for CodeIgniter 2.1

codeigniterPHP

I am using CodeIgniter Version 2.1 & trying to link assets like images,stylesheets, javascript files etc in my views by using, header.php:

<link href="<?php base_url();?>css/style.css" rel="stylesheet" />

my controller code, calls the view:

<?php
class Main extends CI_Controller{
    public function index() {
        $this->load->view('header');
}
  • The view file from which I am trying to load the asset is located
    ../application/views/header.php.
  • the css file is loaded:
    ../application/views/css/style.css

this does not work. I get 404 – Page not found error.then, I tried moving css/style.css outside ../application directory in webroot. To my surpise, having assets in webroot(outsite ../application/views) seems to work nicely.

Now,
My Question is

  1. Is having our assets directly in webroot, outsite ../application directory right approach? If YES/NO, then why?
  2. If having assets directly in webroot is a good idea, than should I move ../application/views directory in webroot as well? How?

PS: I am new to CodeIgniter framework, so unaware of the best practices

Best Answer

If you see this, the section where .htaccess is used to remove index.php from the urls, that has a rewrite condition:

 RewriteCond $1 !^(index\.php|images|robots\.txt)

In this line, images is a folder that will be ignored while mod-rewriting. So, you can replace it by assets, put all your directly linking files there, and happily use them.

 RewriteCond $1 !^(index\.php|assets|robots\.txt)

EDIT: my bad, hadn't seen the date the question was asked. nevertheless, should be useful for someone.

Related Topic