How to Redirect based on Referrer in Apache


redirect based on referrer in apache

HTTP referrer is a request header that tells your web server where your website visitors are coming from. You can use this information to redirect visitors and bots based to different subdomains, folders and even microsites. Apache stores this information in HTTP_REFERER server variable. Let us take a look at how to redirect based on referrer in Apache.

 

How to Redirect based on Referrer in Apache

Here are the steps to redirect based on referrer 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 Referrer

Let’s say you want to redirect all traffic from stackoverflow.com to a new domain www.new-domain.com, then add the following lines to your .htaccess file.


RewriteEngine On
RewriteCond %{HTTP_REFERER} .*stackoverflow.com.*$
RewriteRule ^(.*)$ http://new-domain.com/

 

In the above code, mod_rewrite matches the domain name in HTTP_REFERER environment variable and redirects traffic accordingly.

 

You can also add the above lines to your virtual host’s configuration file.

If you want to redirect based on multiple referrer websites, use the [OR] operator to combine them


RewriteEngine On
RewriteCond %{HTTP_REFERER} .*ubuntuforums.org.*$ [OR]
RewriteCond %{HTTP_REFERER} .*stackoverflow.com.*$ [OR]
RewriteCond %{HTTP_REFERER} .*sourceforge.net.*$ [OR]
RewriteCond %{HTTP_REFERER} .*ubuntu.ru.*$ [OR]
RewriteCond %{HTTP_REFERER} .*python.org.*$ [OR]
RewriteRule ^(.*)$ http://new-domain.com/

 

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 based on http referrer information in request headers. You can use this technique to redirect visitors to specific landing pages, based on their referrer. You can also use this method to block or redirect malicious traffic from your website.

 

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!