How to Redirect Based on Host Name in Apache


redirect based on host name in apache

If you want to personalize user experience for visitors coming from a specific site, you can simply redirect them to tailor-made websites and landing pages, based on the host name in their browser request. Let us take a look at how to redirect based on host name in Apache.

 

How to Redirect Based on Host Name in Apache

Here are the steps to redirect based on host name in apache.

Before you proceed, please ensure that you have enabled .htaccess (mod_rewrite) in Apache. If not, then here’s how you can do it:

 

Place your .htaccess file in the root document folder of your website (/var/www/html)

 

1. Open .htacces file

Open your .htaccess file in a text editor.


$ sudo vim /var/www/html/.htaccess

 

 

2. Redirect based on host name

Let’s say you want to redirect all traffic coming from a specific website www.domain1.com to another domain www.domain2.com, add the following code to your .htaccess file

RewriteEngine On
RewriteCond %{HTTP_HOST} www.domain.com [NC]
RewriteRule ^.*$ http://www.domain2.com%{REQUEST_URI} [R=301,L]

 

Please Note: If you have setup separate virtual host files for each domain in Apache, then update the <VirtualHost> block in their respective files, with the ones shown above.

 

If you want to remove the query string in your requests and send all traffic to one page (e.g www.domain2.com) then simply remove REQUEST_URI from above code,

RewriteEngine On
RewriteCond %{HTTP_HOST} www.domain.com [NC]
RewriteRule ^.*$ http://www.domain2.com [R=301,L]

 

3. Restart Apache web server

Restart Apache web server to apply changes


$ sudo /etc/init.d/apache2 start [Debian or Ubuntu]
# sudo apachectl restart [RHEL, CentOS or Fedora]

 

That’s it! Now Apache will automatically redirect all traffic coming from www.domain1.com and send it to www.domain2.com

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!