affiliate_link

Tuesday, July 17, 2012

Permanent (301) redirection in PHP

Following is the code for permanent (301) redirect using php.
Better approach is to use .htaccess but there are situations where .htaccess could not be used so using following code might help

@header("HTTP/1.1 301 Moved Permanently");
@header("location: http://www.mywebsite.com");

Additionally if you want to redirect your home page to always open using www. which might be usefull when using cookies or for SEO. Add an if condition to code 

if (!preg_match('/www\..*?/', $_SERVER['HTTP_HOST']))
{
    @header("HTTP/1.1 301 Moved Permanently");
    @header("location: http://www." . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
}

No comments: