首页 > 解决方案 > 用于社交媒体抓取的 php .htaccess 重定向页面

问题描述

我有一个从这里得到的 htaccess 代码

场景是,如果访问来自社交媒体网站代理,那么它应该重定向到 autorender.php。

例如:如果社交媒体爬虫尝试访问https://mywebsite.com/details/23。然后它应该重定向到 autorender 页面https://mywebsite.com/autorender.php?id=23。但是,如果访问来自普通用户,它可以转到 url。它是为丰富的社交媒体共享选项而完成的。
我的问题是当我尝试在我的 Facebook 帖子中使用网址https://mywebsite.com/details/23时,它显示找不到页面。 在此处输入图像描述

我的 .htaccess 代码如下

<ifModule mod_rewrite.c>
 RewriteEngine On

# allow social media crawlers to work by redirecting them to a server-rendered static version on the page
RewriteCond %{HTTP_USER_AGENT} (facebookexternalhit/[0-9]|Twitterbot|Pinterest|Google.*snippet)
RewriteRule details/(\d*)$ https://mywebsite.com/autorender.php?id=$1 [P]


# Required to allow direct-linking of pages so they can be processed by Angular
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]  
RewriteCond %{REQUEST_FILENAME} -d  
RewriteRule ^ - [L]

# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]  

</ifModule>

和 autorender.php 文件

<?php

$APIBASE = "https://api.mywebsite.com/";
$id;
if(isset($_GET['id'])){
     $id = $_GET['id'];
     $jsonData = getData($APIBASE , $id);

}

function getData($apiBase, $id ) {
$rawData = file_get_contents($apiBase."api/getPostbyIdGet.php?pid=".$id);
return json_decode($rawData);
}
makePage($jsonData, $APIBASE ,"https://mywebsite.com/details/".$id);
function makePage($data, $siteRoot, $redirectUrl) {

?>
<!DOCTYPE html>
            <html>
                       <head>
                                  <meta property="og:title" content="<?php echo $data[0]->postname; ?>" />
                                  <meta property="og:description" content="<?php echo $data[0]->description; ?>" />
<meta property="og:url" content="<?php echo $redirectUrl ?>" />
 </head>
<body>
<h2><?php echo $data[0]->postname; ?></h2>
<p><?php echo $data[0]->description; ?></p>
</body>

</html>
<?php
}
?>

ps:php版本5.3

标签: php.htaccessmod-rewrite

解决方案


推荐阅读