什麼是 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