0

I am trying to force WWW. into my domain name, but by using PHP vs. HTACCESS like I have below. Is there any issues by doing it with PHP vs. HTACCESS? Does anyone have any code on how to set this up in the best possible manor?

#for all requests on mydomain.com
RewriteCond %{HTTP_HOST} mydomain\.ca$ [NC]
#if they are not for the www.mydomain.com
RewriteCond %{HTTP_HOST} !^www\.mydomain\.ca$ [NC]
#301 redirect to www.mydomain.com
RewriteRule (.*) http://www.mydomain.ca/$1 [R=301,L]
Justin
  • 2,348
  • 6
  • 39
  • 71

2 Answers2

4

For enforcing www in your url, if possible .htaccess should be your choice. It will give you better performance!! Anyway, if you really want to use php code for this you can use following code snippet:

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

For more generic .htaccess redirect code would be

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Here is the reference

  1. htaccess
  2. PHP redirect
medskill
  • 281
  • 3
  • 12
xiidea
  • 3,204
  • 17
  • 23
  • That was exactly what I was looking for. The HTACCESS Generic, that works even better.... thanks. – Justin Apr 30 '14 at 16:43
1

Is this what you want?

$domain= $_SERVER["SERVER_NAME"];
$uri=$_SERVER["REQUEST_URI"]; 
if($domain == "example.com"){
    header("Location: www.example.com$uri");
}
Jeremy
  • 2,346
  • 8
  • 39
  • 73