Search code examples
phpmod-rewriteuser-accounts

mod_rewrite with user account in URL best method


I'm in the process of developing a site that handles user accounts in the following manner:

  • www.mysite.com/username
  • www.mysite.com/username/user-action

I understand the basics with mod_rewrite and that I could do something like:

RewriteRule ^(/*)/?$ /index.php?username=$1 [QSA,L]

However, how does this work with other directories in my site? I have other URLS like:

  • www.mysite.com/about
  • www.mysite.com/contact

Do I just always assume that the first "directory" in the URL is a username and then try to validate that? Then if it doesn't validate, don't do anything... seems like a lot of unnecessary hits on the DB. Also, if that is the case, then how do I handle navigating to those other pages because it's really /index.php?username=about at that point... I want it going to /about... which is then a loop!


Solution

  • Use RewriteCond as so:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(/*)/?$ /index.php?username=$1 [QSA,L]
    

    This RewriteCond first checks to see if the file actually exists, and if so does not apply the rewrite rule. Otherwise will rewrite your URL.

    Of course, depending on your situation there are other approaches that may be more appropriate. But generally, instead of taking the approach of checking whether a user exists in the database, do the opposite: check if it's a valid first-level directory/category, and if not only then assume that it's a user.

    Another option would be to have all the static content in a sub-directory /site/contact /site/about. That greatly simplifies the issue of maintaining in the case that you will often be changing the amount of content sections on the site. Example rewrite condition:

    RewriteCond %{REQUEST_URI} !(site/) [NC]
    

    And then you can have another rewrite rule that applies to site/ in case you want to map that to a CMS or something.

    And finally, I recommend considering using a web framework (Symofony, yii, CodeIgniter), as once you get the hang of it they enable you to develop faster, and in some cases have flexible rewrite/routing rules built in.