每日切割 Nginx 訪問日志,需提取百度、Google、360、搜狗、必應等主流搜索引擎爬蟲產生的 404 鏈接,生成報告文件供 SEO 分析。
s=引擎標識 選擇 User-Agent 關鍵字GET ... HTTP/1.1" 404 ... UserAgent 模式引擎_年月日.txttest.php<?php
// 訪問:test.php?s=google
$domain = 'https://www.example.com';
$spiders = [
'baidu' => 'Baiduspider',
'360' => '360Spider',
'google' => 'Googlebot',
'soso' => 'Sosospider',
'sogou' => 'Sogou web spider',
'easou' => 'EasouSpider',
'bing' => 'bingbot'
];
// 日志路徑:/home/nginx/logs/2024/01/15/access_www.txt
$date = date('Y/m/').(date('d')-1);
$path = "/home/nginx/logs/{$date}/access_www.txt";
$s = $_GET['s'] ?? '';
if (!isset($spiders[$s])) die('Invalid spider');
$spider = $spiders[$s];
$file = "{$s}_".date('ymd', strtotime('-1 day')).'.txt';
// 快取:避免重複解析
if (!file_exists($file)) {
$content = file_get_contents($path);
// 匹配 GET 請求 + 404 + 目標 UA
$pattern = '/GET\s+(\S+)\s+HTTP\/1\.1"\s+404.*'.$spider.'/';
preg_match_all($pattern, $content, $matches);
$out = '';
foreach ($matches[1] as $url) {
$out .= $domain.$url."\r\n";
}
file_put_contents($file, $out);
}
$url = $domain.'/silian/'.$file;
echo $url;
?>
/GET\s+(\S+)\s+HTTP\/1\.1"\s+404.*Baiduspider/ // GET /path HTTP/1.1" 404 ... Baiduspider // 捕獲組 (\S+) 為請求路徑
/silian/test.php)test.php?s=baidu 獲取百度 404 報鏈接fopen/fgets 避免內存溢出parallel 擴展