隔壁酚酞大佬向我抱怨说博客头像加载不出来,要我赶紧想想办法。具体情况如下图。

好家伙,因为日常挂代理的原因,我一直没注意到。清光缓存看了眼自己的。

得,是必须要解决的严重问题。

琢磨并测试了下,头像崩掉单纯是 Gra­vatar 服务在国内不好使的原因。因此只要使用国内的公共 CDN 服务,或是自己建一个,再替换掉 Type­cho 程序中的原有链接,就能解决这个问题。

替换原有链接

在博客根目录 /var/Typecho/Common.php 中,使用 VS­CODE 或是其他编辑器,快捷键 Ctrl+F 搜索 secure.gravatar.com。Type­cho 版本不同,位置可能会不一样,我的在 991 行左右。

$url = $isSecure ? 'https://secure.gravatar.com' : 'http://www.gravatar.com'; $url .= '/avatar/';

搜索下可用的公共 CDN

把第一行里头的链接替换掉

$url = $isSecure ? 'https://sdn.geekzu.org/avatar/' : 'https://cdn.v2ex.com/gravatar/';

因为上面的 CDN 链接里已经带有 /avatar/ 了,所以需要注释掉这一行,也可以把这行直接删掉。

//$url .= '/avatar/';

然后保存,刷新,一切恢复正常。

但是更新 Type­cho 的时候覆盖了怎么办?还有一个方法,在博客根目录程序配置文件 config.inc.php 最后面插一段:

/**自定义头像源*/ define('__TYPECHO_GRAVATAR_PREFIX__', 'https://cdn.v2ex.com/gravatar/');

这个配置文件一般情况不会去动它,所以是最一劳永逸的方法,也推荐使用这个方法。

自己反代一个

直接开一个二级域名用来反代当然可以,但用二级目录(如 himiku.com/avatar/)来反代也不错。参考「Gravatar 镜像资源及 Nginx 反代教程」的方法自己尝试了下。

在配置开头加个缓存,毕竟有缓存又快又能省钱。比如把缓存放在 /home/wwwcache/gravatar

proxy_cache_path /home/wwwcache/gravatar levels=1:2 keys_zone=gravatar:5m inactive=30m max_size=50m;

然后在 server 段里头加个反代。比如我想用 https://www.himiku.com/avatar/,来直接反代 https://secure.gravatar.com/avatar/

location /avatar/ { proxy_pass https://secure.gravatar.com/avatar/; proxy_redirect off; proxy_set_header Host secure.gravatar.com; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Accept-Encoding ""; proxy_cache gravatar; proxy_cache_key $scheme$host$request_uri; proxy_cache_valid 200 304 3h; proxy_cache_valid 301 24h; proxy_cache_valid 500 502 503 504 0s; proxy_cache_valid any 3h; }

不喜欢用 avatar,改用 touxiang 也行,把第一行 location /avatar/ 改成 location /touxiang/ 就好了。

完整些的大致如下。

proxy_cache_path /home/wwwcache/gravatar levels=1:2 keys_zone=gravatar:5m inactive=30m max_size=50m; server { listen 80; server_name himiku.com ; return 301 https://himiku.com$request_uri; } server { listen 443 ssl http2; server_name himiku.com; index index.html; ssl........ 省略 location /avatar/ { proxy_pass https://secure.gravatar.com/avatar/; proxy_redirect off; proxy_set_header Host secure.gravatar.com; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Accept-Encoding ""; proxy_cache gravatar; proxy_cache_key $scheme$host$request_uri; proxy_cache_valid 200 304 3h; proxy_cache_valid 301 24h; proxy_cache_valid 500 502 503 504 0s; proxy_cache_valid any 3h; } …… 其他省略 }

重复上一步,把自己的链接替换进去就行了。

若是想使用我的反代服务,可以点开评论区头像自行获取链接。但是不保证长期稳定。准备停止服务啦,有看到的小伙伴们还请切换到公共 cdn!