Apache – Redirect Domain

Sometimes we may want to have more than one domain name and all point to the same website. This can be done by setting up a rewrite in the Apache VirtualHost setting.
Assume we have setup a website with domain abc.com using the following VirtualHost setting.

<VirtualHost *:80>
	ServerName abc.com
	ServerAlias www.abc.com
	DocumentRoot /var/www/abc
	<Directory /var/www/abc>
		AllowOverride all
		Options FollowSymLinks
	</Directory>
</VirtualHost>

 

We now have another domain name called def.com which is also pointing to the above webserver. So we need to setup another VirtualHost such that whenever some request def.com/www.def.com, he or she will be redirected to http://www.abc.com.

# Redirect def.com to abc.com
<VirtualHost *:80>
	ServerName def.com
	ServerAlias www.def.com
	DocumentRoot /var/www/abc
	<Directory /var/www/abc>
		RewriteEngine on
		RewriteCond %{HTTP_HOST} ^def\.com
		RewriteRule ^(.*)$ http://www.abc.com/$1 [R=permanent,L]
	</Directory>
</VirtualHost>

 

Please remember to enable the mod_rewrite in your Apache server, otherwise def.com/www.def.com will not be written but they will still point to the same website as they have the same DocumentRoot as abc.com/www.abc.com.

Done =)

Update @ 2011-07-11: Modify the rewrite rule as follow

<VirtualHost *:80>
	ServerName def.com
	ServerAlias www.def.com
	DocumentRoot /var/www/abc
	<Directory /var/www/abc>
		RewriteEngine on
		#RedirectMatch ^/$ http://www.abc.com/
		RewriteCond %{HTTP_HOST} ^def\.com
		RewriteRule ^(.*)$ http://www.abc.com/$1 [R=permanent,L]
	</Directory>
</VirtualHost>

 

Reference: Apache redirect domain.com to www.domain.com

Advertisements

2 thoughts on “Apache – Redirect Domain”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.