我们在论坛上发一各帖子,就是一张图片,若是我们不想让别人下载此图片,可以对此图片设置防盗链!

valid_referers none blocked *.test.com *.123.com;
        if ($invalid_referer) {
        return 403;
        }

除了匹配到这两个*.test.com  *.123.com域名外,别的均不能访问!

这个防盗链可以和前面配置的静态缓存过期时间那部分配置结合起来,如下:

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;
        }       
    }

结合之后整个虚拟主机配置文件如下:

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;
    }
    
    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命令来测试一下:

[[email protected] vhosts]# curl -e "http://www.test.com" -x127.0.0.1:80 "http://www.test.com/data/p_w_upload/forum/201701/04/142317dh9fav9kfwor3odf.jpg" -I
HTTP/1.1 200 OK
Server: nginx/1.4.4
Date: Wed, 04 Jan 2017 06:40:05 GMT
Content-Type: p_w_picpath/jpeg
Content-Length: 80837
Last-Modified: Wed, 04 Jan 2017 06:23:17 GMT
Connection: keep-alive
ETag: "586c94d5-13bc5"
Expires: Thu, 19 Jan 2017 06:40:05 GMT
Cache-Control: max-age=1296000
Accept-Ranges: bytes

[[email protected] vhosts]# curl -e "http://www.baidu.com/111" -x127.0.0.1:80 "http://www.test.com/data/p_w_upload/forum/201701/04/142317dh9fav9kfwor3odf.jpg" -I
HTTP/1.1 403 Forbidden
Server: nginx/1.4.4
Date: Wed, 04 Jan 2017 06:40:14 GMT
Content-Type: text/html
Content-Length: 168
Connection: keep-alive

[[email protected] vhosts]#