Thursday, 7 June 2012

Removing index.php from codeigniter URLs


CodeIgniter (CI) is one of the MVC frameworks available. Unlike legacy PHP technique, This framework use different URI format for sending and receive parameters. For example: if we use usual PHP technique, we will use URI like:

localhost/index.php?id=2
But in CI, the URI would be look like this:

localhost/index.php/welcome/2
Where index.php is the router, welcome is the controller, and 2 is the parameter given to the welcome controller. It’s because of its design pattern, the MVC (Model-View Controller).
After some reads, there were a lot of discussion on removing the “index.php” in CI forum. And I’ve been spending my time just to figure it out. I found some good resources at CodeIgniter Wikis, and after some trial-and-error, finally it works for me. This is how I do it:
  1. I created .htaccess file and put it on my CI installation folder. If you used Windows, you could use Save As… menu from Notepad to create this file.
    My CI installation folder was www/igniter, so I put the .htaccess file on this folder. And this is my .htaccess file:
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /igniter
    
    #Removes access to the system folder by users.
    #Additionally this will allow you to create a System.php 
    controller,
    #previously this would not have been possible.
    #‘system’ can be replaced if you have renamed your 
    #system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php/$1 [L]
    
    #Checks to see if the user is attempting to access a 
    #valid file,such as an image or css document, if this 
    #isn’t true it sends the request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    #This last condition enables access to the images and css 
    #folders, and the robots.txt file
    #Submitted by Michael Radlmaier (mradlmaier)
    RewriteCond $1 !^(index\.php|images|robots\.txt|css)
    RewriteRule ^(.*)$ index.php/$1 [L]
    </IfModule>
    
    <IfModule !mod_rewrite.c>
    # If we don’t have mod_rewrite installed, all 404’s
    # can be sent to index.php, and everything works as normal.
    # Submitted by: ElliotHaughin
    
    ErrorDocument 404 /index.php
    </IfModule>


    I just copy-paste the code from CI’s Wiki and modified the RewriteBase into my CI installation folder (in my case: igniter)
  2. Then, I opened the system/application/config/config.php file. I modified the $config['index_page'] from
    1$config['index_page'] = "index.php";
    into
    1$config['index_page'] = '';
  3. I activated mod_rewrite on the Apache. I opened the httpd.conf file and delete the # character in front of:
    1LoadModule rewrite_module modules/mod_rewrite.so
  4. I didn’t need to modified the directory section of httpd.conf file. Maybe it had been already configured by the Apache.
And it worked for me.

No comments:

Post a Comment