On Monday I wrote about several reasons to cloak links. Basically, I argued that cloaking links for the right reasons (managing link destinations and click tracking) meant that link cloaking was a great idea.
Of course, the idea that link cloaking is useful is supported by the number of link cloaking software solutions out there. While you can certainly go out and purchase a link cloaking solution, you can do it for free. In this article, I show you how to cloak your links for free.
How Cloak Links
Basically, the trick to link cloaking is to use your .htaccess file to redirect links targeted at a special subdirectory to a simple php program. That php program parses the link text to grab a keyword, and redirects the link based on that. For example, in the link “http://www.latenightim.com/recommends/google”, the word “recommends” represents the special subdirectory and the word google is the keyword that will determine the actual destination link.
To implement this strategy, you need to complete 2 simple steps:
- edit your .htaccess file
- create a simple php program called cloak.php in you web directory.
The .htaccess file is a file at the Apache web server reads to determine things like access permissions. You can also use this tile to “rewrite” incoming URLs. In our case, we will use the “modrewrite” function of apache to change our URL.
Edit your .htacces and add the following code near the top of the file:
# cloak affiliate links
RewriteRule ^recommends/([^./]+)$ cloak.php?req=$1 [L]
This code says to take all incoming URLs containing the word recommends, strip off and save the end of the URL, and pass that value to a program called cloak.php. In our above google example, this directive sees the word “recommends” in the URL and strips off “google”, passing the word “google” to cloak.php.
Redirecting URLs via PHP
"<?php" <== without the quotes
$request_id = $_GET [‘req’];
$myFile = “/your-www-directory/cloak.log”;
$refData = $_SERVER[‘HTTP_REFERER’];
$fh = fopen($myFile, ‘a’) or die(“can’t open log file”);
$stringData = date(“m/d/y”).”,”.$request_id.”,”.$refData.”n”;
fwrite($fh, $stringData );
if (strcasecmp ($request_id, “search”) == 0)
header( ‘Location: http://www.google.com/’ ) ;
if (strcasecmp ($request_id, “find”) == 0)
header( ‘Location: http://www.yahoo.com/’ ) ;
The above code takes the request ID (“google” in our example) and tests it against possible matches “search” and “find”. Each time you want to add a new redirect, just add another if statement.
There are definitely sexier ways to write this code, but this is simple and easier to maintain.
You will note that cloak.php makes a not of all the redirects ir performs in cloak.log. We’ll discuss that in the next post.
By the way, make sure that cloak.php has world execute permission, as apache usually has really limited permission to execute files.
(If you have questions about getting this to work, please post them in the comments. I’ll do my best to respond).