CodeIgniter: mod_rewrite

June 25th, 2008 | by Isern Palaus |

One of the common problems of CodeIgniter is the visual structure of their URLs. We usually have our applications like http://localhost/index.php/controller/function and probably it will look better if was like this http://localhost/controller/function. This common problem have a common solution, it’s very easy and depends of a Apache’s module called mod_rewrite.

First we need to know if mod_rewrite is active on Apache. The easiest way is check the configuration file called httpd.conf and search for: mod_rewrite.so. Probably we will find this line:

LoadModule rewrite_module modules/mod_rewrite.so

It is probably that this line starts with a #, with a # on a config file like this we disallow the access to the module. If starts with this char, simply, remove it and reboot the server. Now, with this line uncommented the Apache’s server will boot mod_rewrite module every time.

Now it’s time to create our configuration file where our index.php file is located. Create a textfile and rename it to .htaccess, write this:

1
2
3
4
5
6
7
8
9
10
11
<IfModule mod_rewrite.c>
          RewriteEngine On
          RewriteBase /
          RewriteCond %{REQUEST_FILENAME} !-f
          RewriteCond %{REQUEST_FILENAME} !-d
          RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
 
<IfModule !mod_rewrite.c>
          ErrorDocument 404 /index.php
</IfModule>

Whats more, now this file rewrite the URL that we write on the browser and adds index.php/ to show the correct file to users. Now it’s time that CodeIgniter write the link (the ones that you can create with anchor()) without the index.php/. Go to config.php file and change $config['index_page']; variable.

From:

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

To:

$config['index_page'] = "";

And all is done, now you have a very clean and good looking (and SEO!) URLs on your browser.

Sponsored Link: Top Ranked MS SQL, MySQL, PostGreSQL WebHosting - Linux/Windows

Share/Save

Tags: , , ,

Post a Comment