How to: Clean username URL's in CodeIgniter

The URI segment system in CodeIgniter is a very handy thing, but sometimes not flexible enough to handle all your URL needs in one go. To have URL's like and still maintain normal URI segment structure, read on.

When most people start work on this, they think about using routes. You could do it this way, but then every time you enter a url such as then router would send the controller name off to check if it is a username. It’s possible you could do a database check and send it back, but that is just annoying.

Another way is hooks, but I am not a fan of over-using hooks as they can create invisible code which confuses other developers.

The way I like to do this is to add a URL suffix in the config file (meaning add .html or similar to the end of all your pages) then anything with only 1 URI segment that does not have a suffix, is a username.

Step 1: Edit application/config/config.php and set the following config setting:

 | URL suffix
 | This option allows you to add a suffix to all URLs generated by CodeIgniter.
 | For more information please see the user guide:
 $config['url_suffix'] = ".html";

Step 2: Add/edit your .htaccess file and add the highlighted rule:

Options +FollowSymLinks
RewriteEngine on
RewriteBase /

# -- Add this rule ---
RewriteCond %{REQUEST_URI} ^/([a-zA-Z0-9_-]+)$
RewriteRule ^(.*)$ index.php/profiles/view/$1 [L]
# End of rule 

# Standard CodeIgniter rule
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

That is basically a standard CI .htaccess with an extra rule in it. Any URI segment 1 with a-z, 0-9, - or _ in it which does not have a URL suffix will go to a controller which will take the username and show the correct profile.

If you have mod_proxy enabled you could even swap the flag [L] with [L,P] to make the URL stay as