Redirect Subdomain to Root Domain in Apache

One key aspect of setting up a website that is search engine friendly is redirecting your subdomain (www.example.com) to your root domain (example.com) or vise versa. The reason you must do this, is because search engines see each domain as a separate site. If two sites have duplicate content you could be penalized in the search rankings or omitted from the index all together.

It doesn’t really matter if you choose the root domain or prefer to append the www subdomain to it, you just need to choose one and stick with it. Setting up the redirect in apache is very simple. Simply add these lines to the virtual host section of the website in your httpd.conf file. Change the HTTP to HTTPS for port 443 or SSL enabled virtual hosts. If you don’t have access to the /etc/httpd/conf/httpd.conf file then you can simply add these lines to a file called .htaccess in the root of your web directory (public_html).

To redirect www.example.com to example.com

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ http://example.com$1 [R=301,L]

To redirect example.com to www.example.com

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com$1 [R=301,L]


Restart apache

/etc/init.d/httpd restart

Test 301 Redirect

Lastly you should check your redirect. You can verify you site by using a 301 redirect checker like this one here.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *