PHP 301 redirect for non-www to www urls

Want to do a 301 redirect for non-www urls to www, simply use php header command like the following syntax:

[php]<?php
if ($_SERVER[‘HTTP_HOST’] != ‘www.abc.com’){
header(“HTTP/1.1 301 Moved Permanently”, true, 301);
header(“Location: http://www.abc.com”.$_SERVER[‘REQUEST_URI’]);
}
?>[/php]

And for www to non-www:

[php]<?php
if ($_SERVER[‘HTTP_HOST’] != ‘abc.com’){
header(“HTTP/1.1 301 Moved Permanently”, true, 301);
header(“Location: http://abc.com”.$_SERVER[‘REQUEST_URI’]);
}
?>[/php]

This is extremely useful, where you don’t want to use .htaccess file. But remember to put the code on all pages where you actually required the redirect.

By | 2017-09-03T11:38:16+00:00 April 19th, 2014|PHP, Programming|0 Comments

About the Author:

I am a web developer based in Karachi, Pakistan. I have a passion for creating websites which look good on desktops, tablets and mobiles equally. I am making websites and desktop applications since 2004. I have an experience in front-end and back-end development. I enjoy learning new tools and technologies to expand my development potential. So, I love to work on a challenging project which teaches me something new. I have a diverse skill set, ranging from responsive design, HTML, CSS, Javascript to PHP/MYSQL, custom CMS/CRM development and Linux server administration. Are you a business seeking a web presence or an employer looking to hire, get in touch with me here.

Leave A Comment

*