天天看點

LNMP搭建13:Nginx禁止指定user_agent

當需要禁止一些不太重要的通路,如爬蟲等,可以編輯虛拟主機配置檔案

[[email protected] vhosts]# vim test.conf

修改為如下樣式,~*表示不區分大小寫,|表示或者,将含有特定字元串的user_agent禁掉

server

{

   listen 80;

   server_name www.test.com www.aaa.com www.bbb.com;

   if ($host != 'www.test.com')

   {

       rewrite ^/(.*)$ http://www.test.com/$1 permanent;

   }

   index index.html index.htm index.php;

   root /data/www;

   access_log /tmp/access.log combined_realip;

   #deny 127.0.0.1;

   #deny 192.168.147.0/24;

   if ($http_user_agent ~* 'baidu|1111')

   {

       return 403;

   }

   location ~ .*admin\.php$ {

       #auth_basic "aminglinux auth";

       #auth_basic_user_file /usr/local/nginx/conf/.htpasswd;

       allow 127.0.0.1;

       deny all;

       include fastcgi_params;

       fastcgi_pass unix:/tmp/www.sock;

       fastcgi_index index.php;

       fastcgi_param SCRIPT_FILENAME /data/www$fastcgi_script_name;

   }

   location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|rar|zip|gz|bz2)$

……

檢查沒錯後重新加載配置

[[email protected] vhosts]# /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

[[email protected] vhosts]# /usr/local/nginx/sbin/nginx -s reload

用curl測試

[[email protected] vhosts]# curl -x192.168.147.137:80 www.test.com -I

HTTP/1.1 403 Forbidden

Server: nginx/1.6.2

Date: Fri, 24 Feb 2017 21:56:48 GMT

Content-Type: text/html

Content-Length: 168

Connection: keep-alive

這裡我們還需要使用curl進行測試,是以去掉禁止curl通路:

使用-A選項指定http_user_agent

[[email protected] vhosts]# curl -x192.168.147.137:80 www.test.com -I

HTTP/1.1 301 Moved Permanently

Server: nginx/1.6.2

Date: Fri, 24 Feb 2017 21:59:23 GMT

Content-Type: text/html

Connection: keep-alive

X-Powered-By: PHP/5.4.37

location: forum.php

含有baidu的http_user_agent通路被禁止:

[[email protected] vhosts]# curl -A "www.baidu.com" -x192.168.147.137:80 www.test.com -I

HTTP/1.1 403 Forbidden

Server: nginx/1.6.2

Date: Fri, 24 Feb 2017 21:59:55 GMT

Content-Type: text/html

Content-Length: 168

Connection: keep-alive

沒有禁止的http_user_agent可以通路:

[[email protected] vhosts]# curl -A "google" -x192.168.147.137:80 www.test.com -I

HTTP/1.1 301 Moved Permanently

Server: nginx/1.6.2

Date: Fri, 24 Feb 2017 22:00:48 GMT

Content-Type: text/html

Connection: keep-alive

X-Powered-By: PHP/5.4.37

location: forum.php

含有1111的http_user_agent也被禁止:

[[email protected] vhosts]# curl -A "google1111" -x192.168.147.137:80 www.test.com -I

HTTP/1.1 403 Forbidden

Server: nginx/1.6.2

Date: Fri, 24 Feb 2017 22:00:57 GMT

Content-Type: text/html

Content-Length: 168

Connection: keep-alive

轉載于:https://blog.51cto.com/rachy/1901174