網站維護中,監控搜索引擎爬蟲抓取的 404 頁面至關重要,有助於發現死鏈、修復收錄問題、優化 SEO。本文提供一個實用的 PHP 腳本,自動解析 Nginx 日誌,按搜索引擎分類提取 404 URL,生成可直接提交站長平台的報告文件。
GET ... HTTP/1.1" 404 且包含目標爬蟲 UA 的行。<?php
// 配置區域
$domain = 'https://www.example.com'; // 替換為你的域名
$spiders = array(
'baidu' => 'Baiduspider',
'360' => '360Spider',
'google' => 'Googlebot',
'soso' => 'Sosospider',
'sogou' => 'Sogou web spider',
'easou' => 'EasouSpider',
'bing' => 'bingbot'
);
// 日誌路徑結構:/home/nginx/logs/年/月/日/access_www.txt
$yesterday = date('d') - 1;
$logPath = '/home/nginx/logs/' . date('Y/m/') . $yesterday . '/access_www.txt';
// 獲取查詢參數 ?s=baidu
$s = $_GET['s'] ?? '';
if (!array_key_exists($s, $spiders)) {
die('參數錯誤:請指定有效的搜索引擎標識,如 ?s=google');
}
$spiderUA = $spiders[$s];
// 輸出文件名:引擎_年月日.txt
$outFile = $s . '_' . date('ym') . $yesterday . '.txt';
// 若報告不存在則生成
if (!file_exists($outFile)) {
// 讀取日誌(大文件建議用 fopen/fgets 流式讀取)
$content = file_get_contents($logPath);
// 正則匹配:GET HTTP/1.1" 404 ... SpiderUA
// 注意:實際日誌格式需根據你的 log_format 調整正則
$pattern = '/GET\s+(\S+)\s+HTTP\/1\.1"\s+404.*' . preg_quote($spiderUA, '/') . '/';
preg_match_all($pattern, $content, $matches);
$output = '';
foreach ($matches[1] as $url) {
$output .= $domain . $url . "\r\n";
}
file_put_contents($outFile, $output);
echo "報告生成完成:{$outFile}\n";
} else {
echo "報告已存在:{$outFile}\n";
}
// 輸出可訪問的下載鏈接(需配置 Web 服務器允許訪問 silian 目錄)
$downloadUrl = $domain . '/silian/' . $outFile;
echo "下載地址: {$downloadUrl}";
?>
Nginx 默認 combined 格式:
$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"
$request 格式為 GET /path HTTP/1.1。上述正則假設此格式,**實際部署必須根據你的 log_format 配置調整正則表達式**。
file_get_contents 會將整個日誌讀入記憶體,日誌超過 100MB 易導致 OOM。推薦流式讀取:
$handle = fopen($logPath, 'r');
$output = '';
while (($line = fgets($handle)) !== false) {
if (strpos($line, ' 404 ') !== false && strpos($line, $spiderUA) !== false) {
// 簡單提取 URL(根據實際格式解析)
if (preg_match('/GET\s+(\S+)\s+HTTP\/1\.1"/', $line, $m)) {
$output .= $domain . $m[1] . "\r\n";
}
}
}
fclose($handle);
file_put_contents($outFile, $output);
配置 Crontab 每天凌晨自動生成所有引擎報告:
# 每天 01:00 執行
0 1 * * * /usr/bin/php /path/to/test.php s=baidu
0 1 * * * /usr/bin/php /path/to/test.php s=google
# ... 其他引擎
# 或寫一個 wrapper 腳本遍歷 $spiders 陣列一次性生成
location /silian/ { internal; } 僅允許內部重定向訪問。百度/Google/搜狗等提供死鏈提交 API,可擴展腳本:
這個腳本雖簡單,但解決了實際痛點:將龐大、雜亂的原始日誌轉化為結構化、可行動的 404 死鏈報告。通過正則優化、流式讀取、定時任務、安全防護等工程化手段,可構建穩健的 SEO 監控體系,幫助網站及時發現並修復爬蟲遇到的死鏈,提升收錄健康度。