Nginx防盜鏈目錄概要
- 配置以下,能夠和上面的配置結合起來
location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip|doc|pdf|gz|bz2|jpeg|bmp|xls)$ { expires 7d; valid_referers none blocked server_names *.test.com ; if ($invalid_referer) { return 403; } access_log off; }
Nginx防盜鏈
- Nginx防盜鏈配置須要和不記錄日誌和過時時間結合在一塊兒,由於都用到了「location」
- 打開配置文件 vim /usr/local/nginx/conf/vhost/test.com.conf
- 註釋掉一些配置
#location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ #{ # expires 7d; # access_log off; #}
添加一些配置css
location ~* ^.+.(gif|jpg|png|swf|flv|rar|zip|doc|pdf|gz|bz2|jpeg|bmp|xls)$ { expires 7d; //過時時間7天 valid_referers none blocked server_names *.test.com ; //定義一個白名單,referer就是指一些域名 if ($invalid_referer) { //若是不是白名單裏的 return 403; //返回403 } access_log off; }
最後結果以下html
[root@hf-01 ~]# vim /usr/local/nginx/conf/vhost/test.com.conf server { listen 80; server_name test.com test1.com test2.com; root /data/wwwroot/test.com; if ($host != 'test.com' ) { rewrite ^/(.*)$ http://test.com/$1 permanent; } #location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ #{ # expires 7d; # access_log off; #} location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip|doc|pdf|gz|bz2|jpeg|bmp|xls)$ { expires 7d; valid_referers none blocked server_names *.test.com ; if ($invalid_referer) { return 403; } access_log off; } location ~ .*\.(js|css)$ { expires 12h; access_log off; } access_log /tmp/test.com.log combined_realip; } 保存退出
- 添加的配置中的 ~* 表示不區分大小寫,另外防盜鏈的配置裏面server_names能夠不寫照樣
- 檢查配置文件語法錯誤,並從新加載配置文件
[root@hf-01 ~]# /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 [root@hf-01 ~]# /usr/local/nginx/sbin/nginx -s reload [root@hf-01 ~]#
- 測試
[root@hf-01 ~]# curl -x127.0.0.1:80 -I test.com/1.gif HTTP/1.1 200 OK Server: nginx/1.12.1 Date: Thu, 04 Jan 2018 22:50:02 GMT Content-Type: image/gif Content-Length: 8 Last-Modified: Thu, 04 Jan 2018 21:50:34 GMT Connection: keep-alive ETag: "5a4ea1aa-8" Expires: Thu, 11 Jan 2018 22:50:02 GMT Cache-Control: max-age=604800 Accept-Ranges: bytes [root@hf-01 ~]#
- 測試防盜鏈,使用curl -e
[root@hf-01 ~]# curl -e "http://www.baidu.com/1.txt" -x127.0.0.1:80 -I test.com/1.gif HTTP/1.1 403 Forbidden Server: nginx/1.12.1 Date: Thu, 04 Jan 2018 22:51:54 GMT Content-Type: text/html Content-Length: 169 Connection: keep-alive [root@hf-01 ~]# curl -e "http://www.test.com/1.txt" -x127.0.0.1:80 -I test.com/1.gif HTTP/1.1 200 OK Server: nginx/1.12.1 Date: Thu, 04 Jan 2018 22:52:22 GMT Content-Type: image/gif Content-Length: 8 Last-Modified: Thu, 04 Jan 2018 21:50:34 GMT Connection: keep-alive ETag: "5a4ea1aa-8" Expires: Thu, 11 Jan 2018 22:52:22 GMT Cache-Control: max-age=604800 Accept-Ranges: bytes [root@hf-01 ~]#
- 再訪問curl -e "http://www.baidu.com/1.txt" -x127.0.0.1:80 -I test.com/1.gif顯示403,而在訪問curl -e "http://www.test.com/1.txt" -x127.0.0.1:80 -I test.com/1.gif顯示200,則表示防盜鏈配置成功