您的位置:首页 > 运维架构 > Nginx

nginx根据user_agent做访问控制

2017-01-07 14:56 351 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  nginx