CodeIgniter routes and .htaccess


CodeIgniter has a robust routing module as part of its MVC architecture. A trap for the inexperienced arises when the default controller works (e.g. site.com) but anything else such as mysite.com/dashboard goes to a server based 404, not the CodeIgniter one.

Solution: in your config.php file ensure this line is present
$config['index_page'] = '';
and place the following code in an .htacess file
Options -Indexes
Options +FollowSymLinks

# Set the default file for indexes
DirectoryIndex index.php

<IfModule mod_rewrite.c>

# activate URL rewriting
RewriteEngine on

# do not rewrite links to the documentation, assets and public files (your folders here)
RewriteCond $1 !^(images|assets|uploads|js)

# do not rewrite for php files in the document root, robots.txt or the maintenance page etc
RewriteCond $1 !^([^\..]+\.php|robots\.txt|maintenance\.html)

# rewrite everything else
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.

ErrorDocument 404 index.php

</IfModule>

5 thoughts on “CodeIgniter routes and .htaccess”

  1. How work with modules in production ?
    For example site.com/admin ?

    On my local machine works fine, but on server not:
    RewriteCond %{REQUEST_URI} admin
    RewriteRule ^(.*)$ index.php?/$1 [L]

  2. Hi! I need to override Codeigniter routing for an specific uri.

    With Apache and PHP FPM, I will me sending to https://mywebsite/website-status the server status, which works perfectly on non codeigniter sites URLS but with CI it shows the 404 view when accessing /status.

    How can I exclude this URI from Codeigniter?

    Best.

  3. If you want a specific route (url) to be served up directly without CodeIgniter being instantiated I’d do something along the lines of adding a rewrite condition in your .htaccess before your main CodeIgniter rule:

    # This regex is not complete but hopefully you get the idea for what you’re trying to achieve
    RewriteCond $1 website-status

    # Rewrite everything else to CodeIgniter
    RewriteRule ^(.*)$ index.php/$1 [L]

Leave a Comment

Your email address will not be published. Required fields are marked *