Depending on what you need it for, a cleaner solution might be to make sure you serve consistent URL's first. To redirect all http://yoursite.com to http://www.yoursite.com put this in your .htaccess file (in root directory assuming your using apache).
RewriteEngine On
RewriteCond %{HTTP_HOST} ^your-site.com [NC]
RewriteRule ^(.*)$ http://www.your-site.com/$1 [L,R=301]
More variations of this code herehere. This also helps a little with SEO, and is generally good practice.