HTTP Referer based redirects in Apache

Referer HTTP header is a HTTP request field tellling the page the browser was on prior clicking link on it. It answers the question “where the user is coming from to my site”. Also the browsers use it for telling on which page images and other media was referred or embedded in.  The most common use case using HTTP Referer redicts is prevent image hot linking, but I had a use case where I’d like to migrate some traffic to a new domain, based on where the traffic is coming from. A referer based redirect is a solution for this.

HTTP Referer header is HTTP_REFERER environment variable in Apache mod_rewrite procesing context.

Here is a sample snippet which you can toss into virtualhost conf or .htaccess. It matches domain name in any part of HTTP referer (path part too) so it is not water-proof, but for 99,99% cases it works. If the user is coming to some of the mentioned domains the user will be redirected to the new site.

RewriteEngine On
RewriteCond %{HTTP_REFERER} .*plone.org.*$ [OR]
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]
RewriteCond %{HTTP_REFERER} .*kotelett.no.*$
RewriteRule ^(.*)$ http://opensourcehacker.com/

More info

(I hate it when Apache cannot suggest links to the current version of documentation)

\"\" Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+

Leave a Reply

Your email address will not be published. Required fields are marked *