PHP Force www Subdomain

Like this blog? Consider exploring one of our sponsored banner ads...

Sometimes you do not want users to access your domain without the www. If you want to force www.yourdomain.com and redirect yourdomain.com to www.yourdomain.com here is a simple way to do it:

if ((strpos($_SERVER['HTTP_HOST'],'www.')===false)) { header('Location: http://www.yourdomain.com'); exit(); }

You would use this especially for SEO where you did not want to be indexed both ways. Also depending on your framework and the way urls are read, you may need to stay consistent. Just place this code at the top of your page and you are good to go.


About this entry