如何实现FB分享指定og标签,点击跳转含锚点的URL?
需求可行,以下是修复方案
你的思路没问题——用中间页给FB爬虫返回专属OG标签,给普通用户跳转到带锚点的单页地址,但现有代码存在两个关键问题导致跳转失效:
- PHP语法错误:
header('Location: ...'), exit;里的逗号应该是分号,导致exit语句未执行,非爬虫请求可能仍会输出HTML内容而非跳转 - UA判断不完整:FB的爬虫UA不止
facebookexternalhit/1.1,还包括Facebot等,漏判会导致FB爬虫被错误跳转
修正后的完整代码
<?php // 匹配FB所有常见爬虫UA $fbUAs = ['facebookexternalhit/', 'Facebot']; $isFbCrawler = false; foreach ($fbUAs as $ua) { if (strpos($_SERVER['HTTP_USER_AGENT'], $ua) !== false) { $isFbCrawler = true; break; } } // 非FB爬虫则跳转目标锚点地址 if (!$isFbCrawler) { header('Location: https://www.somedomainhere.com/#someAnchorHere01'); exit; // 必须确保退出,避免输出后续HTML } ?> <!DOCTYPE html> <html lang="sk"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Socnets sharer</title> <meta name="description" content="Sharer temp page." /> <!-- 固定og:url为当前中间页地址,FB会以此作为分享的唯一标识 --> <meta property="og:url" content="https://www.somedomainhere.com/php/_socnetshare-someNameHere01.php" /> <meta property="og:title" content="SOME TITLE HERE" /> <meta property="og:description" content="SOME DESCRIPTION HERE." /> <meta property="og:image" content="https://www.somedomainhere.com/img/some-image-here-fb.jpg" /> <meta property="og:image:width" content="1920" /> <meta property="og:image:height" content="1080" /> <meta property="og:image:type" content="image/jpeg" /> <!-- 备用HTML跳转,防止PHP header失效(比如服务器配置问题) --> <meta http-equiv="refresh" content="0; url=https://www.somedomainhere.com/#someAnchorHere01"> </head> <body> <!-- JS备用跳转 --> <script> window.location.href = 'https://www.somedomainhere.com/#someAnchorHere01'; </script> </body> </html>
额外注意事项
- 刷新FB缓存:修改代码后,必须在FB Debugger中输入中间页URL,点击「Scrape Again」,强制FB更新缓存的OG信息
- ShareThis配置:确保ShareThis分享按钮指向的是这个中间页的URL,而非主站地址
- 锚点有效性:主站的锚点
#someAnchorHere01必须对应页面中真实存在的元素ID,否则跳转后不会定位到目标板块
内容的提问来源于stack exchange,提问作者fafa
相关产品推荐
相关产品推荐

