Post 22: CodeIgniter (Removing index.php file)

When using CI (PHP Framework), you will notice that CI includes index.php in the URL for any link to any file.  When you search for this issue by typing: “ci remove index.php from url”, you will see the link to Ellislab user guide  that describes how to fix or solve it as shown in the image below:

image for CI Help
image for CI Help

Now the explanation is very simple and clear, but unfortunately is not complete! In this post, I will try to show you what I’ve learned and did to get my project links to work without including index.php in the URL.

Step1:
When you first install CI, you will notice the .htaccess file is inside a subfolder called “Application”. You need to move it (.htaccess) to the root folder of your project. For example, if your CI website is inside a subfolder named “myproject”: www.mywebsite.com/myproject, .httaccess has to be inside myprojet folder (directory).

Step2:
Open .htaccess, clear it then write or copy the following code:

RewriteEngine On

RewriteBase /myproject/

RewriteCond %{REQUEST_URI} ^system.*

RewriteRule ^(.*)$ /index.php?/$1 [L]

RewriteCond %{REQUEST_URI} ^application.*

RewriteRule ^(.*)$ /index.php?/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?/$1 [L]

ErrorDocument 404 /index.php

Notice that in the second line of the code, the CI website name is myproject. You need to change it based on your project root folder name.

Step3:
Open config.php file here is the path for this file:

Myproject/application/config/config.php

First:

You will see the following comment plus $config[‘base_url’]

// the config[base url] file is the root folder name and anything before that:

Change the value of $config[‘base_url’] to:

For localhost (on your pc):
$config[‘base_url’] = ‘http://localhost/myproject/’;

For your online server:
$config[‘base_url’] = ‘http://www.mydomain.com/myproject/’;

Second:

In the same file (config.php), you will see the line: $config[‘index_page’] = ‘index.php’;

Remove the index.php as shown below:

$config[‘index_page’] = ”;

Step4:
I assume you have your main navigation links inside php template file named header, navigation, or any name you chose. You need to change the links in your main nav to look like this:

<li><a href=”<?php echo base_url();?>mainsite/home”>home</a></li>

mainsite is your main controller name
home is the function name inside your mainsite controller that load home page from the view folder

And that’s it, I hope my post was helpful and easy to understand