Reputation: 2530
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]
Upvotes: 0
Views: 3235
Reputation: 3394
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
Upvotes: 5
Reputation: 2536
Is this what you want?
$domain= $_SERVER["SERVER_NAME"];
$uri=$_SERVER["REQUEST_URI"];
if($domain == "example.com"){
header("Location: www.example.com$uri");
}
Upvotes: 1