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 ~ .*\.(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; //过期时间7天
valid_referers none blocked server_names *.test.com ; //定义一个白名单,referer就是指一些域名
if ($invalid_referer) { //如果不是白名单里的
return 403; //返回403
}
access_log off;
}
最后结果如下
[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;
}
保存退出
[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 ~]#
[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 ~]#