Subscribe to Tutorial Feed

Flash and PHP Bible

The Flash and PHP Bible has been released! The book can be found on Amazon or wherever fine books are sold in your area.

The Flash and PHP Bible has a forum for quick support.

Scriptplayground » tutorials » apache » Redirect to new domain

Redirect to new domain

How to redirect to a new domain, but preserving the requested page.

Even so often you move your site to a new domain but with the search engines moving so quickly you need to make sure the "old" links still work. You can of course do this with META tags in HTML, but those don't work for images or really any non-web page file.

Of course Apache does offer some powerful tools, one of which being the RewriteEngine, this requires the mod_rewrite module to be intalled in your version of Apache. If you don't have you will need to add it or contact your host.

This redirect is a simple directive placed in a ".htaccess" file, and would look something like this.

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^(www\.)?scriptplayground\.com
RewriteRule (.*)$1 [R=301,L]

The 1st line tells Apache that we will be using the rewrite module and to enable it.

The 2nd line tells Apache where this rewrite is to be used, in this example we want the entire public section of the site redirected.

Line 3 is where the redirect really starts to form. Tell Apache to look at the host info "domain name" and check it for the domain we want to redirect. The "(www\.)?" portion means to check for domain names with and without the "www". The "\" are used to escape characters that are used in redirect patterns. In this example we want to look for a dot "." in the url but "." can also mean match all if you are defining a search pattern.

The last line is where the redirect occurs, but we must first capture any page or directory parts, and we do this with "(.*)" which grabs the path portion of the url. The "$1" in the redirected url is what we found in the path. The last step in this line is to setup a valid redirection code and the "L" means this is the last directive.

Thats all there is to setting up a redirect in Apache. I actually just used this on to move it from the staging ground on my development system.

Follow Scriptplayground on Twitter (@scriptplay)

Comments: Redirect to new domain

 takien  Tue Jun 23, 2009 1:31 pm  
why this code not work on my website? just redirected to, not to

 Download  Tue Feb 16, 2010 3:55 pm  
Cool :)
Add a comment
The ability to add new comments has been disabled in this archived version.

Main | Tutorials | Articles