PHP and Htacess Redirect

PHP Redirect Also .htacess Redirect (updated)

This tutorial will demonstrate how to use PHP to perform a redirect. We will be using the PHP header function to send the HTTP headers required to perform the redirect. Note that the header function must must be called before any other output in your PHP script.

Location Header

The Location header is used to redirect the user agent (i.e. web browser, search engine spider, etc.) to some other URL. The following PHP code can be used to send the Location header:

?php
header("Location: http://www.yourdomain.com/newpage.php");
exit;
?

When the PHP header function sends this header, it will also send the temporary redirect (302) status code. The temporary redirect status code tells the user agent to continue to use the original URL.

Permanent Redirect

Often, you will want to send a permanent redirect (301) status code. A permanent redirect status code tells the user agent that the old URL should be discarded and the new URL should be used from now on. To send a permanent redirect status code, send the HTTP header before sending the Location header.

?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.yourdomain.com/newpage.php");
exit;
?

If you are using Apache HTTP server, these types of redirects can also be configured in a .htaccess file. Our .htaccess Tutorial describes how to configure a redirect in this manner.

Conditional Redirect

You can also use PHP code to send the redirect based on some desired condition. For example, the following code will only send the redirect if the user agent was referred from a specified domain:

?php
$referer = $_SERVER['HTTP_REFERER'];
$domain_name = "somedomain.com";
if(strpos($referer, $domain_name)!== FALSE) {
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: http://www.yourdomain.com/newpage.php");
    exit;
}
?
 
.Htacess works on the Apache level.
How this works - if someone visits my site using http://my site.com/ignite-image-gallery,
(notice no www) because of the first step in .htaccess file they will be
redirected to http://www.my site.com/ignite-image-gallery (notice the www) and then because of the joomla
backend redirect they fall on the correct page which is http://www.my site.com/photo-galleries
Code below:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^blacksoldierflyfarming.com$ [NC]
RewriteRule ^(.*)$ http://www.blacksoldierflyfarming.com/$1 [R=301,L]
Source