Nginx配置防盗链
一、修改虚拟主机配置文件,设置白名单网址,其他网址直接拒绝,403
[root@daixuan vhosts]# vim test.conf
server
{
listen 80;
server_name www.test.com www.aaa.com www.bbb.com;
if ($host != 'www.test.com'){
rewrite ^/(.*)$ http://www.test.com/$1 permanent;
}
index index.html index.htm index.php;
root /data/www;
access_log /tmp/access.log daixuan;
location ~ .*admin\.php$ {
auth_basic "daixuan auth";
auth_basic_user_file /usr/local/nginx/conf/.htpasswd;
include fastcgi_params;
fastcgi_pass unix:/tmp/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /data/www$fastcgi_script_name;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
access_log off;
expires 15d;
valid_referers none blocked *.test.com *.aaa.com *.aminglinux.com;
if ($invalid_referer)
{
return 403;
}
}
location ~ .*\.(js|css) {
access_log off;
expires 2h;
}
location ~ (static|cache) {
access_log off;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/tmp/www.sock;
#fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /data/www$fastcgi_script_name;
}
}
valid_referers none blocked *.test.com *.aaa.com *.aminglinux.com; //表示对这些网站不进行盗链,其他网站的访问会按照盗链处理,返回403
二、测试
[root@daixuan vhosts]# /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@daixuan vhosts]# /etc/init.d/nginx reload
重新载入 Nginx: [确定]
[root@daixuan vhosts]# /etc/init.d/nginx restart
停止 Nginx: [确定]
正在启动 Nginx: [确定]
[root@daixuan vhosts]# curl -e "http://www.aminglinux.com/1111" -I -x127.0.0.1:80 'http://www.test.com/static/image/common/background.png'
HTTP/1.1 200 OK //www.aminglinux.com在白名单中,200访问正常
Server: nginx/1.8.0
[root@daixuan vhosts]# curl -e "http://www.aminglinux123.com/1111" -I -x127.0.0.1:80 'http://www.test.com/static/image/common/background.png'
HTTP/1.1 403 Forbidden //www.aminglinux123.com不在百度名单中,403拒绝访问
Server: nginx/1.8.0