什么是 Open Graph Protocol?,可以去看这篇文章
像vue的插件,例如vue-head,vue-meta这些可以动态的添加meta标签到head头中,但是我在尝试之后,并没有什么作用,原因是我们在拷贝链接到国外的一些社交软件时,例如Facebook,Twitter等,这时候是没法执行js的。
解决方案:我们的想法是通过服务端渲染,但是我们想的呢是通过配置nginx来访问php文件,通过php来获取动态的信息,例如标题,图片等信息,然后读取我们打包的单页面的html文件,通过拼接字符串,来生成OG标签,然后再输出html文件的内容出去。
网站根目录结构如下:
演示代码如下:
//nginx的主要配置
location / {
root /home/www/suyuanAPI/public/suyaunWeb;
index index.php index.html index.htm;
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_read_timeout 500;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /home/www/suyuanAPI/public/suyaunWeb$fastcgi_script_name;
include fastcgi_params;
}
<?php
$file_path = "./index.html";
$head = '<head>';
if(file_exists($file_path)){
$fp = fopen($file_path,"r");
$str = fread($fp,filesize($file_path));//指定读取大小,这里把整个文件内容读取出来
if($_SERVER['QUERY_STRING'] == 'name=home'){
$new_head = $head . '<meta property=og:title content="这是首页">';
$str = str_replace($head, $new_head, $str);
} else {
$new_head = $head . '<meta property=og:title content="这是个人">';
$str = str_replace($head, $new_head, $str);
}
echo $str;
fclose($fp);
}
?>
代码解析,代码写的比较简陋,主要就是读取文件,然后获取到链接上的参数,替换字符,再拼接字符和对应的OG标签,根据参数的不同生成不同的OG标签,最后输出html