之前用的是v2ex的源,感觉速度不太理想,所以以下代码就诞生了。

header("Content-type:image/png");
$path_info  = $_SERVER['PATH_INFO'];
$path_array = explode('/', $path_info);

$m     = ($path_array[2] != null) ? $path_array[2] : $_GET['m'];
$s     = isset($_GET['s']) ? $_GET['s'] : '60';
$r     = isset($_GET['r']) ? $_GET['r'] : 'g';
$query = http_build_query(array(
    'gravatar_id' => $m,
    'size'        => $s,
    'rating'      => $r,
));

$url = 'https://secure.gravatar.com/avatar/index.php?' . $query;
$ch  = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$res = curl_exec($ch);
echo $res;
curl_close($ch);

演示地址

http://api.kotori.love/gravatar/06a2950d128ec9faf155e28d9e889baa?s=100&r=g
如果要使用缓存的话,Github 上有一个现成的项目。
要应用在 WordPress 中,将以下代码加入 functions.php 中:

function MyAvatar($avatar) {
        $avatar = str_replace(array("www.gravatar.com/avatar","0.gravatar.com/avatar","1.gravatar.com/avatar","2.gravatar.com/avatar","secure.gravatar.com"),"beta.api.kotori.love/gravatar",$avatar);
        return $avatar;
}
add_filter('get_avatar', 'MyAvatar');

Nginx反代配置

http {
  proxy_cache_path  /var/cache/nginx levels=1:2 keys_zone=gravatar:8m max_size=10000m inactive=600m;
  proxy_temp_path /var/cache/nginx/tmp;

  server {
    listen 80;
    server_name ruby-china.org;

    location /avatar {
      proxy_redirect     off;
      proxy_set_header   Host $host;
      proxy_set_header   X-Forwarded-Host $host;
      proxy_set_header   X-Forwarded-Server $host;
      proxy_set_header   X-Real-IP        $remote_addr;
      proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
      proxy_pass         http://gravatar.com;
      proxy_cache ruby_china;
      proxy_cache_valid  200 302  300d;
      proxy_cache_valid  404 502  1m;
      expires           7d;
    }
  }
}

原文地址