Apache server domain redirection: .config vs .htaccess

There are a few ways to redirect from “Domain A” to “Domain B”. If you do not care about tracking analytics for “Number of Hits” to “Domain A”, the cleanest approach would be to define the redirect in your apache configuration.  Here is an example:



<VirtualHost *:80>
 ServerName www.domainb.com
 DocumentRoot /var/www/domainb.com
 
 <Directory /var/www/domainb.com>
 Options -Indexes +FollowSymLinks -MultiViews
 AllowOverride All
 </Directory>

 CustomLog /var/log/apache2/domainb.com-access.log combined
 ErrorLog /var/log/apache2/domainb.com-error.log
 LogLevel warn
</VirtualHost>


<VirtualHost *:80>
 ServerName domainb.com
 ServerAlias domaina.com www.domaina.com
 RedirectPermanent / http://www.domainb.com/
</VirtualHost>


Here,  the first “VirtualHost” block sets up the new domain “www.domainb.com” .    The second “VirtualHost” block handles redirecting any request for: domaina.com, www.domaina.com and domainb.com to “www.domainb.com”.

This code can be added in a file to your apache config (for example in ubuntu: /etc/apache2/sites-available/domainb.com.conf).  Once added, run “a2ensite domainb.com” to enable it, and then “service apache2 restart” to restart apache server.

The far more often used method of domain redirection is via editing the .htaccess file.  I would use this method If I did not have access to the apache configuration folder.


<IfModule mod_rewrite.c>
RewriteEngine on

RewriteCond %{HTTP_HOST} ^domaina\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.domaina\.com$ [OR]
RewriteCond %{HTTP_HOST} ^domainb\.com$ [OR]
RewriteRule ^(.*)$ http://www.domainb.com/$1 [L,R=301]
</IfModule>

Personally, I prefer to put the configuration in the apache config folder, but decided to share this post to share that both methods are available.

Bookmark the permalink.

Comments are closed.