Pretty URLS With Code Igniter & Mod Rewrite
Code Igniter does a pretty good job of creating pretty urls by default. The basic Code Ignitor address will look like this:
http://www.example.com/index.php/controller/method/parameter
What we want to do is get that index.php out of there. We’ll accomplish this by creating an .htaccess file in our root directory and use it to rewrite the address with Apache’s Mod Rewrite Engine.
Here’s a sample .htaccess file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <ifModule mod_rewrite.c> RewriteEngine On RewriteBase / #We want to prevent users from #accessing our system folder RewriteCond %{REQUEST_URI} ^/system.* RewriteRule ^(.*)$ /index.php/$1 [L] #Next we want visitors to be able #to access real files on our site #such as images or css files. RewriteCond %{REQUEST_FILENAME} !-f #We also want users to be able to #get into directories that may contain #extra files or a separate application #for example /resources or /blog. RewriteCond %{REQUEST_FILENAME} !-d #Finally we want to send everything #after the domain name to Code #Igniter's index.php for processing. RewriteRule ^(.*)$ index.php/$1 [L] </ifModule> |
Next we need to let Code Igniter know that it shouldn’t put index.php in any of it’s urls. We do that by modifying the configuration file at: system/application/config/config.php. We want to find the line of code that looks like this:
1 | $config['index_page'] = "index.php"; |
And change it to look like this:
1 | $config['index_page'] = ""; |
You’ll also have to ensure that Apache is properly configured. Make sure that your apache configuration file contains the load module command:
1 | LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so |
AND that your directory is set up to allow .htaccess directives:
1 2 3 4 | <directory "/path/to/htdocs"> Options FollowSymLinks AllowOverride FileInfo </directory> |
Once these steps are complete, your Code Igniter installation should be able to process urls that don’t contain index.php.
Nice Site!