if ($http_user_agent ~ 'curl|baidu|1111')
    {
       return 403;
    }

如果user_agent是curl,baidu,1111,那么就不能访问网站:

整个配置文件如下:

server
{
    listen      80;
    server_name www.test.com  www.123.com;
    index       index.html index.htm index.php;
    root        /data/www;
    access_log  /tmp/logs/access_log  test; 

    if ($host != 'www.test.com') {
        rewrite ^/(.*)$ http://www.test.com/$1 permanent;
    }


    location ~ .*forum\.php$ {

        auth_basic             "auth";
        auth_basic_user_file  /usr/local/nginx/conf/htpasswd;
        include fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /data/www$fastcgi_script_name;
    }
   
    #user_agent设置
    if ($http_user_agent ~ 'curl|baidu|1111')
    {
       return 403;
    }
 
    location ~ .*\.(gif|jpg|png|jpeg|bmp|swf)$ {
        expires     15d;
        access_log  off;
      #防盗链设置如下
        valid_referers none blocked *.test.com *.123.com;
        if ($invalid_referer) {
        return 403;
        }       
    }

    location ~ \.php$ { 
        include fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /data/www$fastcgi_script_name;
    }

}

加载配置文件,可以用curl来模拟用户标识:

-A 后面跟上模拟的用户标识
[root@lnmp vhosts]# curl -A "1111" -x127.0.0.1:80 http://www.test.com -I  
HTTP/1.1 403 Forbidden
Server: nginx/1.4.4
Date: Wed, 04 Jan 2017 06:50:45 GMT
Content-Type: text/html
Content-Length: 168
Connection: keep-alive

[root@lnmp vhosts]# curl -A "gfdgsfdg" -x127.0.0.1:80 http://www.test.com -I  #未被设置,可以访问
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.4
Date: Wed, 04 Jan 2017 06:50:52 GMT
Content-Type: text/html
Connection: keep-alive
X-Powered-By: PHP/5.3.27
location: forum.php

[root@lnmp vhosts]# curl -A "baidu" -x127.0.0.1:80 http://www.test.com -I
HTTP/1.1 403 Forbidden
Server: nginx/1.4.4
Date: Wed, 04 Jan 2017 06:51:09 GMT
Content-Type: text/html
Content-Length: 168
Connection: keep-alive

[root@lnmp vhosts]# curl  -x127.0.0.1:80 http://www.test.com -I   #默认标识为curl
HTTP/1.1 403 Forbidden
Server: nginx/1.4.4
Date: Wed, 04 Jan 2017 06:51:18 GMT
Content-Type: text/html
Content-Length: 168
Connection: keep-alive

[root@lnmp vhosts]# curl -A "gavafddafsv"  -x127.0.0.1:80 http://www.test.com -I  #可以访问
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.4
Date: Wed, 04 Jan 2017 06:51:29 GMT
Content-Type: text/html
Connection: keep-alive
X-Powered-By: PHP/5.3.27
location: forum.php