首页 网页模板教程 网站网页教程 通过JavaScript实现PC端只允许百度蜘蛛抓取而其他请求返 ...
0赞
赞赏
手机版
扫码打开手机版
把文字装进口袋

通过JavaScript实现PC端只允许百度蜘蛛抓取而其他请求返回404

小妖花满楼满fx  2023-12-6 14:51:29
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script>
  5.     var userAgent = navigator.userAgent.toLowerCase();
  6.     var isMobile = /mobile|android|iphone|ipad|phone/i.test(userAgent);

  7.     if (!isMobile) {
  8.         var isBaiduSpider = /baiduspider/i.test(userAgent);
  9.         if (!isBaiduSpider) {
  10.             window.location.href = "404.html";
  11.         }
  12.     }
  13. </script>
  14. </head>
  15. <body>
  16. <!-- 页面内容 -->
  17. </body>
  18. </html>
复制代码
这段代码的作用是:首先判断用户访问页面的设备类型是否为移动设备(手机、平板等),如果是移动设备,则正常显示页面内容。如果是PC端,再判断用户的浏览器是否为百度蜘蛛(Baidu Spider),如果不是百度蜘蛛,则将页面重定向到一个404错误页面。

注意:这种方式只是基于用户代理字符串进行判断,不能保证100%准确,因为用户代理字符串可以被伪造。
  1. <?php
  2. $userAgent = $_SERVER['HTTP_USER_AGENT'];

  3. // 判断是否为移动设备
  4. function isMobile() {
  5.     $mobileAgents = array(
  6.         'Android', 'iPhone', 'iPad', 'iPod', 'BlackBerry',
  7.         'Windows Phone', 'Symbian', 'Kindle', 'Mobile'
  8.     );
  9.    
  10.     foreach ($mobileAgents as $agent) {
  11.         if (strpos($userAgent, $agent) !== false) {
  12.             return true;
  13.         }
  14.     }
  15.    
  16.     return false;
  17. }

  18. // 判断是否为百度蜘蛛
  19. function isBaiduSpider() {
  20.     $spiders = array(
  21.         'Baiduspider', 'Googlebot', '360Spider', 'YandexBot'//其他要放行的蜘蛛UA放进来,不要的则删掉即可
  22.     );
  23.    
  24.     foreach ($spiders as $spider) {
  25.         if (strpos($userAgent, $spider) !== false) {
  26.             return true;
  27.         }
  28.     }
  29.    
  30.     return false;
  31. }

  32. if (!isMobile()) { // PC端访问
  33.     if (!isBaiduSpider()) { // 非百度蜘蛛
  34.         http_response_code(404);
  35.         exit();
  36.     }
  37. }

  38. // 其他逻辑处理,目前不执行其他代码,也就是放行

  39. ?>
复制代码


使用道具 举报

您需要登录后才可以回帖 立即登录
2024-4-7 00:19:24

返回顶部