php redirect url with og metatag (open graph)

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-28 05:16:05

问题


I have server side redirect page in PHP redirect.php this page redirects the user with PHP header() function:

header( 'location: mypage.html?test' );

Is there a way to add some OG meta tags (Open Graph) in a way that when someone shares the redirect.php page on Facebook and similar websites, these properties would be applied?

<meta property="og:title" content="Facebook should load this when shared redirect.php"/>

回答1:


Since redirect.php redirects whenever it's accessed or/& executed it would be impossible, but with a simple if statement we can allow Facebook Debugger to read the page OG meta tags as below

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');
}

Keep in mind this works only with Facebook bot which causes problems with indexing this page on Google or Twitter, so I suggest you using JavaScript location.href instead.

Reference

  • How to recognize Facebook User-Agent


来源:https://stackoverflow.com/questions/22780212/php-redirect-url-with-og-metatag-open-graph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!