Bulletproof domain redirection for CPanel Add-On domains

Recently I helped my friend Beth Heavrin of Smart Green Tips to migrate her blog to a new domain name. Along the way I realized that the simple way of domain redirection doesn’t work as well for websites that are add-on domains in CPanel environments. This article shows you how to create bulletproof redirects that will work, even for add-on websites.

The Problem

CPanel site structure

In CPanel environments, you start off with a primary domain that resides in the public_html directory. When you add new site to your CPanel hosting, they are added as add-on domains whose root folder are subdirectories of public_html.

You end up with a directory structure in your web hosting account like the image on the right.

Simple .htaccess Redirects Don’t Work

For our example, let’s assume that the primary domain is PrimaryDomain.com and the new domain we want to redirect it to is AddOn1.com. To redirect PrimaryDomain.com to AddOn1.com, you may have used this code in the .htaccess file for PrimaryDomain.com:

# Redirect 301 / http://www.AddOn1.com/

Or, you may have used this code:

# RewriteRule ^(.*) http://www.AddOn1.com/$1 [R=301,L]

With the code above, PrimaryDomain.com will get redirected to AddOn1.com. But unfortunately visitors to AddOn2.com will be wrongly redirected to AddOn1.com/AddOn2.com. Same for other add-on domains within the public_html directory.

This is because AddOn2.com is a subdirectory of public_html. The 2 code snippets above redirect everything, including add-on domain subdirectories to AddOn1.com. Confused? Never mind! Just use the solution below.

The Solution

The solution is to check the hostname (URL) that the visitor is trying to visit before redirecting them. So, let’s update our .htaccess file to the following:

# Redirect PrimaryDomain.com to www.AddOn1.com
RewriteCond %{HTTP_HOST} ^PrimaryDomain.com$
RewriteRule ^(.*)$ http://www.AddOn1.com/$1 [R=301,L]

#Redirect www.PrimaryDomain.com to www.AddOn1.com
RewriteCond %{HTTP_HOST} ^www.PrimaryDomain.com$
RewriteRule ^(.*)$ http://www.AddOn1.com/$1 [R=301,L]

The first block of rules only redirects visitors to PrimaryDomain.com and the second block only redirects visitors to www.PrimaryDomain.com. Visitors to AddOn2.com or AddOn3.com will not be redirected. Solved!


Leave a Reply

%d bloggers like this: