|
本文介绍如何使用 JavaScript 实现 IP 地域屏蔽 和 设备访问控制,并支持 爬虫(蜘蛛)检测。通过解析用户 IP 地址,可限制特定国家/地区的访问,同时识别访问设备类型(如 PC、手机或爬虫),从而增强网站安全性和访问控制。
JS屏蔽指定地区及设备访问代码(含蜘蛛爬虫识别)
代码灵活调整,可指定屏蔽地区、设备、蜘蛛、用户
以下代码移动设备及蜘蛛可正常访问,北京及运城地区的pc端用户无法访问(百度站长工具抓取测试正常)
风险:长期使用可能导致网站降权
- <script type="text/javascript">
- (function () {
- const isPC = !/mobile|android|iphone|ipad|phone/i.test(navigator.userAgent.toLowerCase());// 移动设备
- const isSpider = navigator.userAgent.match(/(bot|spider|crawler)/i) ? 1 : 2;// 爬虫
- if (!isPC || isSpider === 1) return; //移动端及蜘蛛访问正常返回页面
- const controller = new AbortController();// 超时控制器
- const timeout = setTimeout(() => controller.abort(), 3000);
- const error_path = "error.html";// 重定向目标
- function zhi_ding_diqu(province, city){
- return (province.includes('北京') && city.includes('北京')) || (province.includes('山西') && city.includes('运城'));//屏蔽北京和运城
- }
- (async () => {
- try {
- const res = await fetch('https://myip.ipip.net/json', { signal: controller.signal });
- clearTimeout(timeout);
- if (!res.ok) throw new Error('fetch error');
- const { ret, data } = await res.json();
- if (ret === 'ok') {
- const [location, province, city] = data.location;
- if (zhi_ding_diqu(province, city)) {
- window.location.replace(error_path);
- }
- }
- } catch (e) {
- // 上面的方法不能使用自动执行下面的(绵羊优创网本地ip库)
- clearTimeout(timeout);
- console.error(e);
- // 创建并加载脚本
- const script = document.createElement('script');
- script.src = 'http://smy.sheepyc.com/tool/ipku/getipinfo.php?return=ipinfo&format=js';
- script.onload = () => {
- const { province = '', city = '' } = ipinfo || {};
- if (zhi_ding_diqu(province, city)) {
- window.location.replace(error_path);
- }
- };
- script.onerror = () => console.warn('sheep: ipinfo variable is not defined or is null.');
- document.head.appendChild(script);
- }
- })();
- })();
- </script>
复制代码
分享一个简单错误提示页面,可用于跳转后显示:
- <!doctype html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>抱歉,站点已停止</title>
- <style>
- html,body,div,h1,*{margin:0;padding:0;}
- body{background-color:#fefefe;color:#333}
- .box{width:580px;margin:0 auto;}
- h1{font-size:20px;text-align:center;background:url(背景图链接,不需要则删除) no-repeat top center; padding-top:90px;margin-top:30%;font-weight:normal;}
- </style>
- </head>
- <body>
- <div class="box"><h1>抱歉!该站点已停止运行!</h1></div>
- </body>
- </html>
复制代码 为什么写了两个接口判断代码?
默认的ip接口来自网络,若停止更新则不可用,所以增加了判断,若失效则使用绵羊优创网本地ip接口,提升安全性及可用性
为什么不直接使用绵羊优创网本地ip接口?
默认的ip接口有人更新维护ip库,能确保ip保持较新状态,绵羊本地ip库虽然也够用但更新频率低
ip库更新地址:github.com/metowolf/qqwry.dat
(当前绵羊优创网本地ip接口更新时间20250720)
|
|