apache redirect based on hostname

How to Redirect in Apache Based on Hostname

Apache is a powerful web server that allows you to setup complex website configurations easily. It allows you to redirect based on various parameters such as IP address, location, URL, and more. Sometimes you may need to redirect in Apache based on Hostname. In this article, we will look at how to redirect in Apache based on Hostname. You can use these steps to redirect multiple domains or subdomains on a single Apache server.


How to Redirect in Apache Based on Hostname

Here are the steps to redirect in Apache based on Hostname. Basically, we will need to create separate virtual host for domain/subdomain that you want to redirect. Your Apache server will receive requests to all these domains/subdomains on a single server and redirect them based on hostname.

Let us say you want to redirect two domains example1.com and example2.com to www.website1.com and www.website2.com respectively.

Open Virtual Host file in a text editor.

$ sudo vi /etc/apache2/sites-available/000-default.conf

Add the following lines to your virtual host configuration file.

<VirtualHost *:80>
    ServerName example1.com
    ServerAlias www.example1.com
    redirect 301 / http://www.website1.com/
</VirtualHost>

<VirtualHost *:80>
    ServerName example2.com
    ServerAlias wwww.example2.com
    redirect 301 / http://www.website2.com/
</VirtualHost>

In this case, we have created 2 virtual hosts – one for example1.com and other for example2.com. The first virtual host listens to all requests sent to example1.com and redirects them to http://www.website1.com. The second virtual host listens to all requests sent to example2.com and redirects them to http://www.website2.com.

You can easily modify this configuration to redirect subdomains too. You just need to change the Server_Name directive. Here is an example to redirect subdomains blog.example.com to www.website1.com and articles.example.com to www.website2.com.

<VirtualHost *:80>
    ServerName blog.example.com
    redirect 301 / http://www.website1.com/
</VirtualHost>

<VirtualHost *:80>
    ServerName articles.example.com
    ServerAlias wwww.example2.com
    redirect 301 / http://www.website2.com/
</VirtualHost>

You may even use a combination of domains & subdomains above. Save and close the file.

Restart Apache server to apply changes.

$ sudo service apache2 restart

Open browser and visit your domains/subdomains and you will be redirected to the appropriate websites.

Also read :

How to Block URL Pattern in Apache
How to Redirect Port 80 to 8080 in Apache
How to Monitor Apache Performance using mod_status
How to Parse JSON in NodeJS
How to Hide PHP Version in WordPress/Apache

Leave a Reply

Your email address will not be published.