Tumblr in a subdirectory

Written . Tagged PHP.

I now have a tumblelog, powered by Tumblr.

Tumblr seems quite awesome – simple and powerful, just the way I like it. They even offer Tumblr on your own (sub)domain if you can configure your DNS A records.

I didn’t want to use a subdomain, though. My site is on a subdomain already, and sub-subdomains look silly. I don’t like using subdomains directly under nyh.se for personal stuff since it’s not namespaced (I considered svnrik.nyh.se before going with svn.nyh.se for my SVN repository…). Anyway, since Tumblr don’t offer this, I threw together a tiny proxy.

Over at http://henrik.nyh.se/tumble, this is my .htaccess:

.htaccess
1
2
3
4
5
RewriteEngine On
RewriteBase /tumble

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$  proxy.php?url=http://malesca.tumblr.com/$1

and this is proxy.php:

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
27
28
29
30
<?php

$from = "malesca.tumblr.com";
$unto = "henrik.nyh.se/tumble";

// Because Dreamhost doesn't do remote fopens, and to get content-type
function fetch($url) {
  $curl = curl_init();
  $timeout = 5; // set to zero for no timeout
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        $html = curl_exec($curl);
  $content_type = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
  curl_close($curl);
  return array($html, $content_type);
}

list($html, $content_type) = fetch($_GET['url']);

// Fix root-relative links etc.
$html = preg_replace('/\b(href|src|rel)="\//', '$1="http://'.$unto.'/', $html);
// Replace the old URL with the new
$html = str_replace($from, $unto, $html);

header("Content-type: $content_type");
echo $html;

?>

This piece of code just mirrors the content as well as the content-type of anything on http://malesca.tumblr.com to http://henrik.nyh.se/tumble. Fixes links in the RSS feed as well. Pretty neat.

You obviously need a PHP with libcurl.

You’ll likely want to change the $from and $unto values at the top, as well as the URL in the .htaccess rewrite rule.