There are many good reasons to be consistent when using the ‘www’ in URLs. This includes good usability (it may confuse some people when they see it there some of the time but not others) and SEO (some search engines may consider the the same page with the ‘www’ different then the one without it).
The most common way to do it is to use Apache to redirect to the ‘www’ using an .htaccess file with code like the following:
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{HTTP_HOST} !^(www\.|$) [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
That code will force the ‘www’ in all URLs in the directory and subdirectories in which it is placed. Unfortunately that solution isn’t always ideal. Sometimes doing this will break third party software. Also, not all websites run on Apache.
An alternative solution to this is to handle the redirect with PHP itself. To accomplish this we need to check the current URL to see if the ‘www’ is present or not. If not, we’ll reload the page with it in place:
if ((strpos($_SERVER['HTTP_HOST'], 'www.') === false))
{
header('Location: http://www.'.$_SERVER["HTTP_HOST"].'/'.$_SERVER["REQUEST_URI"]);
exit();
}
Noticed this code doesn’t hard code the URL into itself. This means we can use this same code on multiple pages and even change the domain name or entire URL and it will still work. If you wanted to apply this to an entire website you simply only need to include it at the top of every page.
Thank you for this “Use PHP to Force the www on URLs” it really help alot. I cant thank you enough.
Although I had to remove the slash the line 3 to avoid having double slash in Google chrom.
Just like this;
header(‘Location: http://www.’.$_SERVER[“HTTP_HOST”].”.$_SERVER[“REQUEST_URI”]);
Hey thanks so much John Conde. lots of conflict in my case when I did it in htaccess, it worked for me in PHP.