Use PHP to Force www Subdomain to a URL

Writen By Tyler Ingram on Jul 18, 2007

Now if you are looking at a quick tip with SEO (Search Engine Optimization) you might notice that search engines such as Google will index your website twice based on subdomains. What do I mean? If you have ever used Google’s Webmaster Tools you can choose which Preferred Domain Google will crawl but it doesn’t necessarily guarantee that it will index your choice. To help ensure you are only indexed on your preference (in my case I like www.tyleringram.com and not tyleringram.com) you can use PHP with a few simple lines of code to have users redirected to the proper subdomain which in the case of my blog is www.

[code]
<?php

if(strpos($_SERVER['HTTP_HOST'], 'www.') === false) {

  header("Location: http://www.mydomain.com{$_SERVER['REQUEST_URI'}");
  exit();
}
?>
[/code]

 

Now where would you put this code?

Depending on how your blog or website works you would want it to be one of the very first things to be loaded in the scripts. In my case I put it into the header of my blog which deal with various things such as header redirects, Session set up and other site wide initiations. This will allow the redirect to happen before any other information is loaded.

What does it do?

Well strpos() will check to see if the first 4 characters are ‘www.’ or not and if they are not then it needs to redirect to the proper subdomain.

Adding $_SERVER[‘REQUEST_URI’] at the end of the URL will allow the user to be redirected to the location they requested with the proper subdomain so they don’t have to re-navigate through you’re blog.

 

Posted in: Uncategorized | 245 views

 5 Comments

  • This is a technique that I always implement, but with .htaccess files. I like doing in in a .htaccess file so that the page doesn’t have to actually be refreshed… the redirect happens within the request.

    For your PHP example, you should put this before your header location so the search engines know there is only one page, not two:

    header(”HTTP/1.1 301 Moved Permanently”);

  • I use a Wordpress plugin for that:

    http://txfx.net/code/wordpress/enforce-www-preference/

    It makes sense you should do it for optimal search results.

  • Thanks for the advice! I was going to add a subdomain to mine, but wasn’t sure how to handle it with for SEO purposes.

  • Derek: Oh yes the 301 redirect, I did that for people who went to my old URL, I guess I could do it for this as well. Good Point

    Damien: Thanks for posting the Wordpress plugin, I am sure people will find that useful since I’d say like 90% of bloggers use WordPress. I could be wrong though hehe but most people I know use WordPress

    Justin: Thanks for visiting!

  • buddy thanks for the great tip

Leave a Reply