編輯虛擬主機配置文件
[root@LampLinux ~]# vim /usr/local/nginx/conf/vhosts/test.conf
在上一節全局訪問控制配置deny 192.168.137.0/24;下面添加:
#deny 127.0.0.1;
#deny 192.168.137.0/24;
if ($http_user_agent ~* 'curl|baidu|yyyyy') # ~* 表示“不區分大小”寫匹配
{
return 403;
}
我們去測試怎麼模擬user_agent,爲了防止影響,要先把“訪問控制”的內容註釋“#”掉:
重加載:
[root@LampLinux ~]# /usr/local/nginx/sbin/nginx -t
[root@LampLinux ~]# /usr/local/nginx/sbin/nginx -s reload
測試:
[root@LampLinux ~]# curl -x192.168.137.11:80 www.test.com/forum.php -I
HTTP/1.1 403 Forbidden
Server: nginx/1.6.2
Date: Wed, 12 Aug 2015 11:40:39 GMT
Content-Type: text/html
Content-Length: 168
Connection: keep-alive
現在去模擬一個user_agent:
[root@LampLinux ~]# curl -A "asdfasdfasfdsf.sdfafsdfaf" -x192.168.137.11:80 www.test.com/forum.php -I
HTTP/1.1 200 OK
Server: nginx/1.6.2
Date: Wed, 12 Aug 2015 11:43:27 GMT
... ...
用在什麼情況下?
你的網站訪問量很大,服務器資源緊缺,我們成本要控制的嚴謹一點,服務器會有一些吃力,網站都會給搜索引擎一個“蜘蛛”去爬取,爬取得時候,跟我們現實去搜索一樣的,同樣也會訪問我們的數據庫,耗費我們的PHP資源,所以我們要把一些不太重要的搜索引擎“蜘蛛爬蟲”給禁止掉,比如我們把360spider、有道或搜狗的spider全部禁止掉,當然我們可以封IP,但是他的IP不固定,很麻煩,所以我們就想到使用user_agent,非常簡單,只要是這裏 ($http_user_agent ~* 'curl|baidu|yyyyy') 包含curl、baidu、yyyyy字段的都 return 403;
實驗:
[root@LampLinux ~]# curl -A "asdfasbaidufdsf.sdfafsdfaf" -x192.168.137.11:80 www.test.com/forum.php -I
HTTP/1.1 403 Forbidden
Server: nginx/1.6.2
Date: Wed, 12 Aug 2015 11:45:10 GMT
Content-Type: text/html
Content-Length: 168
Connection: keep-alive
[root@LampLinux ~]# curl -A "asdfasyyyyyfdsf.sdfafsdfaf" -x192.168.137.11:80 www.test.com/forum.php -I
HTTP/1.1 403 Forbidden
Server: nginx/1.6.2
Date: Wed, 12 Aug 2015 11:47:19 GMT
Content-Type: text/html
Content-Length: 168
Connection: keep-alive