- 打卡等级:常驻代表
- 打卡总天数:40
- 打卡月天数:4
- 打卡总奖励:341
- 最近打卡:2025-07-11 08:55:56
|
Gravatar 头像已经成为了博客、论坛等非常流行的通用头像,他能使你的网站的留言者根据自己的邮箱匹配不同的 Gravatar 头像。但不可否认的是 Gravatar 头像的服务器及缓存服务器位于国外,由于受到了干扰,国内无法打开 Gravatar 头像服务器及缓存服务器,导致了 Gravatar 头像无法显示,这样严重的拖累了网站的打开速度,甚至会因为一篇文章的留言非常多,需要加载几百个 Gravatar 头像图片,大量 HTTP 请求的发送,直接导致了网页加载缓慢、网站出现打不开的现象。
之前用的是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);
复制代码 如果要使用缓存的话,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;
- }
- }
- }
复制代码 原文地址:https://kotori.love/archives/fetch-gravatar-with-php
|
|