So, a month or so ago, I got linked by a fairly high traffic site. Problem was, they just linked an image that appeared in one of my posts. What to do, what to do? Well, I certainly didn’t want people to just hit a hotlinked image all day and I didn’t just want it to give a 404 or 403, RIGHT?!
So I came up with a little .htaccess magic that will make sure your hotlinked visitors always get relevant WordPress content rather than just a crappy image saying please don’t hotlink, or some other worthless thing like that.
I call it smotlink. Because that sounds funny and it’s a combination of smart and hotlink, so it works.
It’s actually a pretty simple piece of code that comes in two parts. Firstly, you put this code at the beginning of your .htaccess file in the root of your wordpress directory.
1 2 3 4 5 6 | RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^http(s)?://.*?\.?yoursitehere.com [NC] RewriteCond %{HTTP_REFERER} !^http(s)?://.*?\.?google.com [NC] RewriteCond %{HTTP_REFERER} !^http(s)?://.*?\.?feedburner.com [NC] RewriteRule /(.*)\.(jpg|jpeg|png|gif)$ smotlink.php?pic=$1\.$2 [L] |
You’ll notice google and shit like that in there, that’s the make sure feed readers and things like that display your images properly. Add any ones you think you might need.
Next, you will need to copy the code below, edit the variables and your site URL, and upload it to the base of your wordpress directory as smotlink.php (the same directory as the .htaccess file from above).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?php $site = 'http://mysite.com'; // Your WordPress blog URL. if(!isset($_GET['pic'])) { header('Location: ' . $site); exit(); } $dbhost = 'localhost'; // WordPress SQL host $dbuser = 'username'; // WordPress DB username $dbpass = 'password'; // WordPress DB password $dbname = 'wordpress_db'; // Name of your WordPress DB $prefix = 'wp_d5fe8e'; // Your WordPress table prefix. mysql_connect($dbhost, $dbuser, $dbpass); mysql_select_db($dbname); // The name of the database $pic = mysql_real_escape_string($_GET['pic']); $sql = "select ID from `" . $prefix . "_posts` WHERE post_status = 'publish' and post_content LIKE '%" . $pic . "%'"; $get = mysql_query($sql); $post = mysql_fetch_array($get); header('Location: ' . $site . '?p=' . $post['ID']); ?> |
Drop a comment if you have any trouble with anything. GOOD TIMES! Please enjoy.