Phil Sturgeon

Web developer, kayaker, outdoors madman and part-time alcoholic.


How to: Clean username URL's in CodeIgniter

Posted CodeIgniter at Jan 19, 2009

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 http://example.com/controller 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: | | http://codeigniter.com/user_guide/general/urls.html */ $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 example.com/username.

Comments

User comments
  • Gravatar Erebraskegree

    Dec 30, 2009

    jrg racing shop http://www.pyzam.com/profile/3311736
    naa national automobile association autozone auto parts website nissan
    mio c520 power on auto http://www.asianave.com/maserati_auto/
    volkswagen jetta change temperture sencor gui automobile guages spyker
    wheel bearing mercedes 420 http://www.testriffic.com/user/nissancar
    mercedes repair manual volkswagen owners manuel maybach
    acadia auto auction group maine ducati parts bumper 2007 dodge motorcycle
    princess racing apparel peugeot volkswagen beetle accessories toyota
    automobile mini fuse panel hummer pimp myspace mercedes radiator
    de soto automobile cadillac automobile ltd in usa subaru

Post a comment