Force the use of the www on a domain

Sometimes it is necessary to redirect all requests to the www subdomain. Here's how to do it (this should be the very first bit of code on the page):

Using .htaccess

RewriteEngine On
RewriteCond %{HTTP_HOST} ^website.co.uk
RewriteRule (.*) http://www.website.co.uk/$1 [R=301,L]

Using php

$host = $_SERVER["HTTP_HOST"];
$host = strtolower($host);
$host = trim($host);
$host = str_replace(':80', ", $host);
$host = trim($host);

if ($host != 'www.domain.com'){
header('HTTP/1.1 301 Moved Permanently');
$url = isset($_SERVER["REQUEST_URI"]) ? $_SERVER["REQUEST_URI"] : ";
header('Location: http://www.domain.com' . $url);
$url = htmlspecialchars($url);
exit;
}

Tags: , ,

About Keiron

Web Developer based in the UK. Click here if you want to work with me