Oct1a

服务器Nginx设置限制IP或设备访问网站

限制IP访问

server{
    allow 127.0.0.1/16; //allow:允许访问
    deny all; //拒绝访问
}

不懂IP段如何计算,这个工具不错:ip计算器 ip地址计算器

限制设备型号访问

server{
  location /{
    if($http_user_agent ~"(HUAWEIVNS-AL00)|(可添加其他关键字)"){
      proxy_pass http://www.xxxx.com
    }
    return 403
  }
}

限制访问的host头

server{
  location /{
    if($host =='www.xxxx.com'){
      proxy_pass http://www.xxxx.com
    }
    return 404
  }
}

限制爬虫,重定向

server{
  if ($http_user_agent ~* (baiduspider|googlebot|Googlebot|soso|bing|sogou|yahoo|sohu-search|yodao|YoudaoBot|robozilla|msnbot)) {
    rewrite ^/(.*)$ https://www.baidu.com permanent;
  }
}

使用map批量设置

下面代码来源:stackExchange

map "$host:$http_user_agent" $my_domain_map_host {
  default                             0;
  "~*^www.domain.com:Agent.*$"        http://www.domain2.com;
  "~*^www.domain2.com:Other Agent$"   http://www.domain3.com;
}

server {
  if ($my_domain_map_host) {
    return 302 $my_domain_map_host$request_uri;
  }
}

设备UA限制代码批量生成,这网站不错
http://detectmobilebrowsers.com/

本作品采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可。