最近在使用 Vercel 的 OG 图生成功能时,遇到了一个棘手的问题:生成的 OG 图在 Twitter 上无法正确显示。本文将分享我排查和解决这个问题的过程,希望能帮助遇到类似问题的朋友。
问题描述
在 Vercel 上配置了 OG 图生成后,访问生成的 URL 可以正常看到图片,但当将该 URL 用作 Twitter 卡片的 og:image
时,Twitter 却无法加载图片,于是我们用 twitter card validator 进行验证,发现报错信息如下:
WARN: The image URL *****/api/og-enhanced?****** specified by the 'twitter:image' metatag may be restricted by the site's robots.txt file, which will prevent Twitter from fetching it.
排查步骤
很明显问题出在了 robots.txt
文件上。我们检查下:
User-agent: *
Allow: /
# Disallow admin and private areas
Disallow: /admin/
Disallow: /api/
Disallow: /user/
# Allow specific endpoints for SEO
Allow: /rss.xml
Allow: /sitemap-index.xml
# Sitemap locations
Sitemap: https://www.dteam.top/sitemap-index.xml
我们发现 /api/
路径被禁止访问,而 Vercel 的 OG 图生成接口正是通过 /api/og-enhanced
提供的,这就导致 Twitter 无法访问该图片,于是我们很自然的想到修改 robots.txt
文件,加一个规则放行不就得了?
Allow: /api/og-enhanced
Disallow: /api/
很遗憾,Twitter 依然无法访问图片,依然报同样的错。但是通过 google 的 robots.txt 测试工具,却能通过验证,说明 robots.txt
语法是正确的。
解决方案
为了规避不同 Bot 对 robots.txt
解析的差异,我们决定将 OG 图生成接口迁移到一个不受 robots.txt
限制的路径下,最终将 /api/og-enhanced
改为 /og-enhanced
,问题解决。
总结
robots.txt
在不同的平台可能有不同的解析策略,所以尽可能不要出现冲突的规则。