redirect pages to www

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
shaam
Forum Newbie
Posts: 20
Joined: Tue Jun 23, 2009 6:36 am

redirect pages to www

Post by shaam »

Hi,
I want to redirect pages e,g 'http://mydomain.com/pagename.html' to 'http://www.mydomain.com/pagename.html",i.e if anyone access without www then it will be added automatically,server is php,how can i do this ?
plz help
Thanks
Bind
Forum Contributor
Posts: 102
Joined: Wed Feb 03, 2010 1:22 am

Re: redirect pages to www

Post by Bind »

Code: Select all

<?php
if(strpos($_SERVER['HTTP_HOST'],'www.')===false)
   {
      header ('HTTP/1.1 301 Moved Permanently'); # optional - to notify search engines and such
      header ('Location: http://www.'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
      exit;
   }
?>
shaam
Forum Newbie
Posts: 20
Joined: Tue Jun 23, 2009 6:36 am

Re: redirect pages to www

Post by shaam »

Thanks for your reply,i have done this with different method using .htaccess,which is working fine,using following code.

Options +FollowSymlinks
RewriteEngine on
rewritecond %{http_host} ^mydomain.com [nc]
rewriterule ^(.*)$ http://www.mydomain.com/$1 [r=301,nc]
shaam
Forum Newbie
Posts: 20
Joined: Tue Jun 23, 2009 6:36 am

Re: redirect pages to www

Post by shaam »

How to do this with javascript instead of php ?
Bind
Forum Contributor
Posts: 102
Joined: Wed Feb 03, 2010 1:22 am

Re: redirect pages to www

Post by Bind »

shaam wrote:How to do this with javascript instead of php ?

Code: Select all

<script language="text/javascript">
var prot = location.protocol;
var host = location.host;
var path = location.pathname;
if(host.indexOf('www.') == -1)
   {
      location.replace(prot+'//www.'+host+path);
   }
</script>
Post Reply