user2360599
user2360599

Reputation: 83

.htaccess redirect from image to article

im trying to redirect traffic i get from reddit to an article, but the image in the article is being hot-linked on reddit.com

this is fine but im wondering if theres a way that when users click on the image on reddit.com with a path like:

http://mysite.com/i/12345.jpg to redirect to http://mysite.com/r/12345

the only site I've noticed to do this successfully is livememe.com which has an image on reddit redirect to the article when clicked on. for example:

http://www.livememe.com/36opcf5.jpg redirects to http://www.livememe.com/36opcf5

and im trying to do something similar. Ive noticed that this redirect occurs whenever you go directly to that url.

Upvotes: 0

Views: 175

Answers (2)

Justin
Justin

Reputation: 33

I know it's been a few months since you asked, but if you still need a solution, I found an answer. Tried to find how it is done for a few hours, but unsuccessfully, so I had to come up with my own solution. Livememe doesn't do that redirect with htaccess, they do it with PHP. Since you can't see the difference in referrer, it would be the same whether the picture is embedded, or user clicks a link to it, you have to check something else. And the only difference I see is HTTP_ACCEPT header. If a resource is used as an image, it won't send HTTP_ACCEPT with a value of "text/html", it will be "image/jpeg" or something like that. So what you do is something like this: first, create .htaccess file with this:

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /redirect.php?q=$1 [L]

So if a file is not found, redrect.php is loaded (wile your URL stays the same). And inside redirect.php put something like this:

$accept = explode(',', $_SERVER['HTTP_ACCEPT']);

$file = $_GET['q'];
$file_info = pathinfo( $file );
$url = $file_info['filename'];
$ext = $file_info['extension'];
$check_html = array_search('text/html', $accept);

if ( file_exists("$url.html") ) {
    if ($check_html !== FALSE) header("location: http://yourdmain.com/$url"); // location of URL you want to redirect to
    else header("location: http://i.yourdomain.com/$url.$ext"); // loction of image file
}
else {
    header('HTTP/1.0 404 Not Found');
    print 'File not found';
}

Adjust according to your server (the file_exists() part). Or you can check the database, to see that such post exists. Well, I think you get the idea, how that is done. Hope that helps.

Upvotes: 0

Lucas Willems
Lucas Willems

Reputation: 7063

Try this code :

RewriteEngine On
RewriteRule ^i/([a-zA-Z0-9]+)\.(jpe?g|JPE?G)$ /r/$1 [R=301]

Upvotes: 1

Related Questions