- <!DOCTYPE html>
- <html>
- <head>
- <script>
- var userAgent = navigator.userAgent.toLowerCase();
- var isMobile = /mobile|android|iphone|ipad|phone/i.test(userAgent);
- if (!isMobile) {
- var isBaiduSpider = /baiduspider/i.test(userAgent);
- if (!isBaiduSpider) {
- window.location.href = "404.html";
- }
- }
- </script>
- </head>
- <body>
- <!-- 页面内容 -->
- </body>
- </html>
复制代码 这段代码的作用是:首先判断用户访问页面的设备类型是否为移动设备(手机、平板等),如果是移动设备,则正常显示页面内容。如果是PC端,再判断用户的浏览器是否为百度蜘蛛(Baidu Spider),如果不是百度蜘蛛,则将页面重定向到一个404错误页面。
注意:这种方式只是基于用户代理字符串进行判断,不能保证100%准确,因为用户代理字符串可以被伪造。
- <?php
- $userAgent = $_SERVER['HTTP_USER_AGENT'];
- // 判断是否为移动设备
- function isMobile() {
- $mobileAgents = array(
- 'Android', 'iPhone', 'iPad', 'iPod', 'BlackBerry',
- 'Windows Phone', 'Symbian', 'Kindle', 'Mobile'
- );
-
- foreach ($mobileAgents as $agent) {
- if (strpos($userAgent, $agent) !== false) {
- return true;
- }
- }
-
- return false;
- }
- // 判断是否为百度蜘蛛
- function isBaiduSpider() {
- $spiders = array(
- 'Baiduspider', 'Googlebot', '360Spider', 'YandexBot'//其他要放行的蜘蛛UA放进来,不要的则删掉即可
- );
-
- foreach ($spiders as $spider) {
- if (strpos($userAgent, $spider) !== false) {
- return true;
- }
- }
-
- return false;
- }
- if (!isMobile()) { // PC端访问
- if (!isBaiduSpider()) { // 非百度蜘蛛
- http_response_code(404);
- exit();
- }
- }
- // 其他逻辑处理,目前不执行其他代码,也就是放行
- ?>
复制代码
|