Here I come with the new article about 301 moves permanently to new URL.Sometimes you want to redirect your visitors to a new URL so, In this article, I will explain about how to make a PHP redirect using the 301 “moved permanently” redirection.
Earlier I have shown that how to Set DirectoryIndex using .htaccess and how to set Expire Headers using .htaccess.
What is 301 redirect ?
A permanent redirect tells the browser that the page has moved permanently which is known as 301 redirections and it is very useful to know search engine that your URL is changed.
Your website is ranked in the search engine and if you make any changes in site URL whereas search engine has this URL and visitor try to access the site from a search engine, get 404 Page not found error.So now you need to send visitors from old URL to new URL. So the solution of this issue is 301 redirection which means URL is moved permanently. 301 redirection is the most powerful and search engine friendly method.
301 redirection using PHP code
If you want to redirect a single page to another URL then add the following code in the old page which have been moved.
1 2 3 4 | header('Location: http://www.domain.com/new-file-name.php'); |
If you want to redirect non-www to www domain name then add the following code into the top of every page of the website.
1 2 3 4 5 6 7 | if (substr(getenv('HTTP_HOST'),0,3) != 'www') { header('HTTP/1.1 301 Moved Permanently'); header('Location:http://www.'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); } |
301 redirection using .htaccess file?
You need to add the following line of code into the .htaccess file and upload it into the root folder of the website.
1 2 3 4 5 | RewriteEngine On RewriteCond %{HTTP_HOST} ^domain\.com RewriteRule (.*) http://www.domain.com/$1 [R=301,L] |
Note: Make sure your website is running under Apache WebServer.
That’s it.You can ask questions by comments if you have any query or issue. Let me know if this solution works for you.