Use PHP to Force the www on URLs
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:
1 2 3 4 | 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:
1 2 3 4 5 | if ((strpos($_SERVER['HTTP_HOST'], 'www.') === false)) { header('Location: http://www.'.$_SERVER["HTTP_HOST"].'/'.$_SERVER["REQUEST_URI"]); exit(); } |
Notice 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.
Related Posts:
Tags: Apache, htaccess, PHP, SEO
July 24th, 2008 at 8:00 am | Posted in Programming