How to remove an index.php file from the Codeigniter URLs?
As we know, a URL in CodeIgniter is designed in such a way that it would be search engine and human friendly, too, rather than using a standard approach to create a URL string. By default, it uses an index.php file in the CodeIgniter’ URLs, as shown below.
localhost/codeigniter3.1.1/index.php/My_controller/
If you want to remove an index.php from a CodeIgniter URL and to generate a standard URL string to run the php file, you must follow these three steps, as shown below.
Step1. In this step, you need to create a .htaccess file in the root folder of CodeIgniter that is parallel to the application folder.
Step2. After creating a file in the application folder, write the following code in a .htaccess, but make sure that your Apache server has enabled mod_rewrite to accept file requests directly to the CodeIgniter URL without using index.php in the URL.
RewriteEngine On RewriteBase /codeIgniter-3.1.11/ // write the root folder name RewriteCond %{REQUEST_URI} ^system.* RewriteRule ^(.*)$ /index.php/$1 [L] RewriteCond %{REQUEST_FILENAME} !-f // it defines the file name RewriteCond %{REQUEST_FILENAME} !-d // it accepts all the directory RewriteRule ^(.*)$ index.php/$1 [L]
Step3. After successfully created a .htaccess file in the CodeIgniter application, now you have to make a small change in the application/config/config file. In this file, there is a $config[‘index_php’] variable that assigned a default ‘index.php’ value. Now remove an ‘index.php’ value from the $config variable and set it to blank as shown below.
$config[‘index_page’] = ‘index.php’; // before setting it to blank $config[‘index_page’] = ‘’; // after set to blank.
Example: Create a MyController.php controller file and save it to the following path application/controller/MyController.php folder. And write the following program in the controller file.
MyController.php
<?php defined('BASEPATH') OR exit( 'No direct script access allowed'); class MyController extends CI_Controller { public function index() { echo "<title>Tutorial and Example </title>"; echo "<h3> It is an Example of remove an index.php file from the CodeIgniter URL </h3>"; } public function test() { echo "<title>Tutorial and Example </title>"; echo "<h4> Welcome to the Tutorial and Example </h4>"; } } ?>
To run the program in the localhost by invoking the URL localhost/CodeIgniter-3.1.11/MyController; it shows the output as shown below.
And in our previous topic, we have used index.php as a URL to execute a controller program in the localhost by invoking a URL localhost/Codeigniter-3.1.11/index.php/MyController, and then call a function, as shown in below image.