首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 統計 Nginx 日志中搜索引擎爬蟲 404 頁面:自動化分析腳本

     編輯:PHP 綜合知識

背景與目標

每日切割 Nginx 訪問日志,需提取百度、Google、360、搜狗、必應等主流搜索引擎爬蟲產生的 404 鏈接,生成報告文件供 SEO 分析。

腳本邏輯

  1. 按日期定位昨日日志文件路徑
  2. 根據查詢參數 s=引擎標識 選擇 User-Agent 關鍵字
  3. 正則提取 GET ... HTTP/1.1" 404 ... UserAgent 模式
  4. 補全域名前綴,寫入 引擎_年月日.txt
  5. 輸出報告下載鏈接

完整代碼 test.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+) 為請求路徑

部署與使用

  1. 放置於 Web 可訪問目錄(如 /silian/test.php)
  2. 確保 PHP 進程有日志目錄讀權限、腳本目錄寫權限
  3. 瀏覽器訪問 test.php?s=baidu 獲取百度 404 報鏈接
  4. 定時任務(cron)每日凌晨自動跑批所有引擎

進階優化

  • 大文件流式讀取:日志超百 MB 時用 fopen/fgets 避免內存溢出
  • 多進程並行:每引擎一進程,或用 parallel 擴展
  • 入庫分析:寫入 MySQL/ClickHouse,支撐趨勢圖、Top N 統計
  • 去重與分類:按 URL 路徑聚合、識別參數雜訊、標記修復優先級
  • 告警機制:404 突增觸發郵件/釘釘通知

注意事項

  1. 日志格式必須為 combined/主流格式,自定義格式需調整正則
  2. User-Agent 關鍵字需隨爬蟲更新維護
  3. 生成報告目錄需防止外部直接遍歷下載(加 .htaccess 或存非 Web 目錄)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved