带有 og 元标记的 php 重定向 url(开放图)

ipe*_*pel 3 php redirect facebook facebook-opengraph

我在 PHP 中有服务器端重定向页面,redirect.php此页面使用 PHPheader()函数重定向用户:

header( 'location: mypage.html?test' );
Run Code Online (Sandbox Code Playgroud)

有没有办法添加一些 OG 元标记(开放图谱),以便当有人redirect.php在 Facebook 和类似网站上共享页面时,将应用这些属性?

<meta property="og:title" content="Facebook should load this when shared redirect.php"/>
Run Code Online (Sandbox Code Playgroud)

Ada*_*zad 6

由于redirect.php在访问或/和执行时重定向是不可能的,但是通过一个简单的if语句,我们可以允许 Facebook Debugger 读取页面 OG 元标记,如下所示

PHP

<?php
if (in_array($_SERVER['HTTP_USER_AGENT'], array(
  'facebookexternalhit/1.1 (+https://www.facebook.com/externalhit_uatext.php)',
  'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
))) {
  header("HTTP/1.1 200 OK");
  print '<html prefix="og: http://ogp.me/ns#">
               <head>
                  <title>{title}</title>
                  <meta property="og:title" content="{OG Title}" />
                  <meta property="og:type" content="website" />
                  <meta property="og:url" content="http://example.com" />
                  <meta property="og:image" content="http://example.com/og_img.jpg" />
              </head>
        </html>';
}
else {
  // You're not Facebook agent '__' 
  header('Location: mypage.html?test');
}
Run Code Online (Sandbox Code Playgroud)

请记住,这仅适用于 Facebook 机器人,这会导致在 Google 或 Twitter 上索引此页面时出现问题,因此我建议您改用 JavaScript location.href

参考