• t
  • g
  • B
  • Z
  • @
  • e

portfolio & blog of senior web developer, Fahd Murtaza



  • About
  • Portfolio
  • WordPress
  • CV
  • Blog
  • Contact


  • About
  • Portfolio
  • WordPress
  • CV
  • Blog
  • Contact

Codeigniter – Clean URLs – Apache mod rewrite : Removing /index.php/ from URL in CodeIgniter Application

August 22nd, 2008 by Fahd

Note: Based on its popularity, updated on 6th june 2011 to clean up code for easy copy paste.

OK readers, here is a simple method to achieve clean urls with your PHP application developed in CodeIgniter.

Please note that this method is applicable only to applications developed in CodeIgniter. Much of the content has been taken from CodeIgniter wiki but rewritten in my own way.

This article explains how to take away “index.php” from your CI application URLs. However, it does NOT remove the need for Index.php, which is the CI front controller i.e. even though Index.php will not appear in the URL, it still needs to be present at the top level of your site (above the /system/ directory). To quote the User Guide,

You can easily remove this file by using a .htaccess file with some simple rules.

You need to perform the following steps to get this working:

  1. Create a .htaccess file to configure the rewrite engine
  2. Set $config['index_page'] to an empty string
  3. Make sure your apache uses the mod_rewrite module
  4. Make sure apache is configured to accept needed .htaccess directives
  5. Restart apache and test

1. Create your .htaccess file

Create a new file named .htaccess and put it in your web directory

RewriteEngine On
RewriteBase /
#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
RewriteRule ^(.*)$ index.php/$1 [L]

# 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

Notes for Windows users:
To create this file you must open Command Prompt and type:

copy con .htaccess [Enter]
[Press CTRL + Z]

A blank .htaccess file will be created. Now you can edit it using Notepad or your favorite text editor and copy the script above.

Note: Most Windows editors will assume that you are attempting to save an .htaccess file as a file with an extension and no filename. The Crimson Editor can be used to create and save .htaccess files and other files that have no filename.

Note: If your site is placed in subfolder specify the path in the “RewriteBase /subfolder/” line.

2. Set $config['index_page'] to an empty string

Open your

system/application/config/config.php

and find the line that assigns $config['index_page'] a value, usually:

$config['index_page'] = "index.php";

and change it to:

$config['index_page'] = '';

Save the file.

3. Make sure your apache has mod_rewrite activated

This means that the apache must be configured to load the mod_rewrite module (or it might have it compiled-in). For module inclusion, usually you have to look for a line like this in httpd.conf or a file loaded by it (hint: use some quick file search utility to grep files with lines containing ‘rewrite’ string):

LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so

If you’re running Apache2 type

a2enmod

in the console and when prompted

rewrite

to enable mod_rewrite.

On a Windows machine this line might look this way:

LoadModule rewrite_module modules/mod_rewrite.so

If it is commented out (# in front), make sure to uncomment it and save the file. Checking if the corresponding module exists may be a good idea as well (but it usually does).

Make sure apache accepts needed .htaccess directives

This means that apache is explicitly configured to allow .htaccess files to override those directives that you use in your .htaccess file from step 1. above.

It seems to be sufficient if you add these two lines to your section where you configure the document root for your CI application:

#...
Options FollowSymLinks

AllowOverride FileInfo
#...

There might be other Options listed, just make sure you have FollowSymLinks as well.

Should you get a 500 Internal Server Error, try the following syntax:

Options Indexes Includes FollowSymLinks MultiViews
AllowOverride AuthConfig FileInfo
Order allow,deny
Allow from all

5. Restart apache and test your application

Works? Congratulations!

Doesn’t work? Ehrrr… well, do not give up; equip yourself with patience, double check all steps above and if it still does not work, post on the forum giving all details of your setup.

How does URL rewriting work?

<IfModule mod_rewrite.c>
...
</IfModule>

Do what is inside only if Apache has the mod_rewrite feature (by in place compilation, or loaded module).

RewriteEngine On

Activate the URL rewriting engine, if not already done (in main Apache configuration file.

RewriteBase /

Define the part of the URL that won’t change nor be used for rewriting. In fact, this part will be removed before processing, and prepended after processing. This’s a good way to use subfolder-independent rewrite rules. For example, if your CodeIgniter index.php is placed in a virtual host directory, like /tests/, set RewriteBase to /tests/.

RewriteCond %{REQUEST_FILENAME} !-f

Condition to meet for RewriteRule activation. Here, we test if the requested filename does not exist.

RewriteCond %{REQUEST_FILENAME} !-d

Same as above, but we test for directory existence.

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

If RewriteCond conditions are met, this rule will be applied. It inserts index.php before the requested URI. The $1 represents the part of string enclosed by parentheses in left expression. The [L] means that this rule is the last one if rule is applied (thus stopping rewriting).

Configuring mod_rewrite in the httpd.conf file

The Apache mod_rewrite docs say

While URL manipulations in per-server context are really fast and efficient, per-directory rewrites are slow and inefficient. If you have access to your httpd.conf file, you’ll have better performance if you configure the rewrite rules in there.

You can add something like this to your httpd.conf:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
RewriteRule ^(.*)$ /index.php/$1 [L]

Configuring mod_rewrite and virtual hosting with Apache 2.2

ServerName www.mydomain.com
DocumentRoot /path/to/ci/directory

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

Credits: http://codeigniter.com/wiki/mod_rewrite/

Posted in Articles, CodeIgniter, Frameworks, PHP, Web Development

18 Comments

  1. CI developer
    Posted December 31, 2008 at 8:10 am | Permalink

    Hi ..
    Thank you so much for this wonderful Blog .. I struggled for more than 8 hours to fix index.php problem .. and when i found this article .. I got it resolved in just 10 minutes ..

    Thanks …

  2. Christian
    Posted January 28, 2009 at 3:31 pm | Permalink

    Hi, thanks for this information. But how about if I have more than 1 applications ? I have index.php for my firstApp, and the second.php for my secondApp.

    Regards

  3. Bjorn Ali
    Posted June 7, 2009 at 5:15 pm | Permalink

    The line breaks between LT and “IfModule !mod_rewrite.c” ruined it for me :-)

  4. Sean Zicari
    Posted September 2, 2009 at 6:14 pm | Permalink

    Excellent post. It helped me get clean URLs going in about 20 mins.

  5. Jin
    Posted April 6, 2010 at 4:25 pm | Permalink

    I’ve been looking around your site and really am impressed by the terrific content here. I work the nightshift at my job and it is boring. I’ve been coming here for the past couple nights and reading. I simply wanted to let you know that I’ve been enjoying what I have seen and I look ahead to reading more.

  6. Wordpress Themes
    Posted April 10, 2010 at 3:22 pm | Permalink

    Good dispatch and this enter helped me alot in my college assignement. Say thank you you seeking your information.

  7. Miami fl lawyer
    Posted July 11, 2010 at 6:45 am | Permalink

    Great post, I learned a lot! Looking forward to checking back soon!

  8. jobe
    Posted August 4, 2010 at 3:07 pm | Permalink

    You idiot, dark blue text on a black background? Good choice!

  9. Richard
    Posted August 20, 2010 at 5:46 am | Permalink

    I have something like this and i want to change using htaccess.
    http://localhost/project/yoozbox-ci/niche_page/display/5
    I want to change into
    http://localhost/project/yoozbox-ci/title of the niche here/id

  10. Fahd
    Posted August 22, 2010 at 12:27 pm | Permalink

    @jobe: Its fixed now :) thanks for the kind comments ;)

  11. Fahd
    Posted August 22, 2010 at 12:28 pm | Permalink

    @Richard: Are you using CodeIgniter?

  12. mossberg
    Posted October 1, 2010 at 12:59 am | Permalink

    I have a from on my home page. When I hit submit on the form, I’m sent to an url without “index.php” but then CI can’t find the controller files to load and I end up with a 404 error.

  13. Fahd
    Posted October 3, 2010 at 12:41 am | Permalink

    @mossberg: Well you can simply define the default controller. Or you can redirect to proper url. See the bottom of this page. http://codeigniter.com/user_guide/helpers/url_helper.html

  14. Victor
    Posted January 11, 2011 at 8:14 pm | Permalink

    @Mossberg. I also had the same problem but was able to resolve id. Instead of the content of Fahd in the htaccess file, I used the content of CI. Its here

    RewriteEngine on
    RewriteCond $1 !^(index\.php|images|css|robots\.txt)
    RewriteRule ^(.*)$ /choice/index.php/$1 [L]

    and It worked!

  15. Victor
    Posted January 11, 2011 at 8:15 pm | Permalink

    Thanks Fahd. You did a great job brother!

  16. doug
    Posted May 17, 2011 at 9:07 pm | Permalink

    why does this have to be so difficult!

  17. Fahd
    Posted May 17, 2011 at 9:34 pm | Permalink

    is it, really?

  18. desta
    Posted November 2, 2011 at 8:40 pm | Permalink

    hai, greate tutorials, but, what while the system of CI in subfolder, i mean like this:
    in /var/www/framework/system_of_ci

    we access to:
    http://localhost/framework/system_of_ci/index.php/welcome

    when i use your trick its nothing… but i get .htaccess tricky…

    with “?” you will clear index.php…

    type: http://localhost/framework/?welcome

    it’s done n work, but why use “?” .. thx.

One Trackback

  1. By green toaster » Blog Archive » Getting ISAPI_Rewrite working on IIS for CodeIgniter on May 6, 2009 at 10:19 pm

    [...] http://www.fahdmurtaza.com/myblog/2008/08/22/codeigniter-clean-urls-apache-mod-rewrite-removing-inde... Comment (RSS)  |  Trackback [...]

Post a Comment

Click here to cancel reply.

Your email is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Categories


Want to Hire Me?


Fahd Murtaza is the guy behind fahdmurtaza.com: your source for getting your web development projects done. Fahd sepcialises in Open Source Web Development and his favorite is WordPress. This site is a platform to his web development portfolio and blog all on a newly designed responsive website—try viewing it on your mobile.

If after viewing Fahd's portfolio, you think he might be just the guy to hire for your web / application development; check out the web development pricing page, then find out how to hire Fahd with a web development project idea and a brief of requirements.

 


Fahd Murtaza has put together a number of Web Development Articles that will help you see what he does, how he does it. You will also be able to see the level of work, and passion, that Fahad puts into each and every job. Understanding a little about the process can make the idea of investing good money much more palatable. People have always appreciated my Agile techniques. Its time you

Fahd Murtaza, Web Developer, Programmer, Wordpress Expert
U
This is portfolio & blog of senior web developer Fahd Murtaza, who has 9 years experience in: website development, WordPress, drupal, CMS and CRM application development with passion of making web better; one site at a time.


@
Mobile +968 93 678 199
email info@fahdmurtaza.com
Google Talk: fahdim@gmail.com
Skype fahd.murtaza
Location Muscat, Oman.


_
Developed using my beloved, love of my life, WordPress, built on the responsive, grid based, mobile optimised, Foundation Framework, and a modified Foundation theme. More Info →


Follow Fahd: Twitter / Google+ / Instagram / Facebook / Dribbble / Tumblr / Posterous /
Copyright © 2006-2012 Fahd Murtaza

    • WordPress.org
    • Documentation
    • Support Forums
    • Feedback