Nginx如何针对user_agent访问控制【附代码】

今天爱分享给大家带来Nginx如何针对user_agent访问控制【附代码】,希望大家能够有所帮助。

[root@minglinux-01 ~] vim /usr/local/nginx/conf/vhost/test.com.conf
···
 45     if ($http_user_agent ~ 'Spider/3.0|YoudaoBot|Tomato')
 46     {
 47       return 403;
 48     }
···

~为匹配符号,只要user_agent中含有Spider/3.0或者YoudaoBot或者Tomato字符串的,都会被拒绝,return 403为直接返回403的状态码,return 403和deny all效果一样。

测试结果:

[root@minglinux-01 ~] /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@minglinux-01 ~] /usr/local/nginx/sbin/nginx -s reload
[root@minglinux-01 ~] curl -x127.0.0.1:80 -A "Tomato" test.com/upload/1.txt -I 
HTTP/1.1 403 Forbidden
Server: nginx/1.12.2
Date: Wed, 28 Nov 2018 14:02:41 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive

[root@minglinux-01 ~] curl -x127.0.0.1:80 -A "tomato" test.com/upload/1.txt -I 
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Wed, 28 Nov 2018 14:02:56 GMT
Content-Type: text/plain
Content-Length: 4
Last-Modified: Wed, 28 Nov 2018 13:53:13 GMT
Connection: keep-alive
ETag: "5bfe9dc9-4"
Accept-Ranges: bytes

人已赞赏
Nginx

Nginx如何根据正则匹配来限制访问【附代码】

2020-10-20 17:31:52

Nginx

Nginx如何解析php相关配置【附代码】

2020-10-20 17:50:10

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
'); })();