標籤:nginx valid_referers 防盜鏈
ngx_http_referer_module模組允許攔截“Referer”要求標頭中含有非法值的請求,阻止它們訪問網站。 需要注意的是偽造一個有效“Referer”要求標頭是相當容易的, 因此這個模組的預期目的不在於徹底地阻止這些非法請求,而是為了阻止由正常瀏覽器發出的大規模此類請求。 還有一點需要注意,即使正常瀏覽器發送的合法請求,也可能沒有“Referer”要求標頭。
文法: valid_referers none | blocked | server_names | string ...;
“Referer”要求標頭為指定值時,內嵌變數$invalid_referer被設定為空白字串, 否則這個變數會被置成“1”。尋找匹配時不區分大小寫。
該指令的參數可以為下面的內容:
none:缺少“Referer”要求標頭;
blocked:“Referer” 要求標頭存在,但是它的值被防火牆或者Proxy 伺服器刪除;這些值都不以“http://” 或者 “https://”字串作為開頭;
server_names:“Referer” 要求標頭包含某個虛擬機器主機名;
string ...:任一字元串定義一個伺服器名和可選的URI首碼。伺服器名允許在開頭或結尾使用“*”符號。 當nginx檢查時,“Referer”要求標頭裡的伺服器連接埠將被忽略。
Regex必須以“~”符號作為開頭。 需要注意的是運算式會從“http://”或者“https://”之後的文本開始匹配。
none:表示referer為空白,比如我們直接在瀏覽器開啟一個網站或者圖片時。
blocked:這個不大好理解,上機做了個測試:
nginx.confg裡的配置為
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { valid_referers blocked www.a.com; if ($invalid_referer) { return 403; }}
用curl進行測試
[[email protected] ~]# curl -x127.0.0.1:80 ‘localhost/static/image/common/logo.png‘ -I -e ‘http://www.a.com‘
HTTP/1.1 200 OK
Server: nginx/1.8.1
Date: Thu, 29 Dec 2016 00:59:44 GMT
Content-Type: image/png
Content-Length: 4425
Last-Modified: Tue, 31 May 2016 03:08:36 GMT
Connection: keep-alive
ETag: "574d0034-1149"
Accept-Ranges: bytes
[[email protected] ~]# curl -x127.0.0.1:80 ‘localhost/static/image/common/logo.png‘ -I -e ‘http://www.b.com‘
HTTP/1.1 403 Forbidden
Server: nginx/1.8.1
Date: Thu, 29 Dec 2016 01:00:09 GMT
Content-Type: text/html
Content-Length: 168
Connection: keep-alive
[[email protected] ~]# curl -x127.0.0.1:80 ‘localhost/static/image/common/logo.png‘ -I -e ‘www.b.com‘
HTTP/1.1 200 OK
Server: nginx/1.8.1
Date: Thu, 29 Dec 2016 01:00:15 GMT
Content-Type: image/png
Content-Length: 4425
Last-Modified: Tue, 31 May 2016 03:08:36 GMT
Connection: keep-alive
ETag: "574d0034-1149"
Accept-Ranges: bytes
通過測試,我的理解是,因為某些防火牆或者Proxy 伺服器會刪除Referer的值,所以無法跟據Referer的值來進行攔截,只要不是以“http://” 或者 “https://”字串作為開頭的Referer都通過,不知道這個觀點對不對。
server_names:指nginx設定檔中設定的虛擬機器主機名;
例如,對除www.a.com,www.b.com外的網站進行防盜鏈:
server { listen 80; server_name www.a.com www.b.com; root /data/www; index index.html index.htm; location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { valid_referers server_names; if ($invalid_referer) { return 403; #rewrite ^/ http://www.example.com/nophoto.gif; } } }
string ...:任一字元串可以用*.example.com,www.example.*等來表示,例如:
valid_referers none blocked *.example.com; valid_referers server_names; if ($invalid_referer) { return 403; }
利用nginx“ngx_http_referer_module”模組設定防盜鏈