nginx配置访问本地物理目录下图片,若不存在则访问远程图片库URL链接,始终没有配置成功,请高手指点!非常感谢

javadeveloper 发布于 2016/04/17 09:37
阅读 1K+
收藏 1

假设存在本地图片目录:/export/home/pic,同时存在远程图片服务(访问方式假设为http://192.168.1.12:80/),若需要访问特定图片1204.jpg,本地绝对路径/export/home/pic/sell/4f407ad7e588e535b012d38b/1204.jpg,远程图片服务URL为http://192.168.1.12:80/sell/4f407ad7e588e535b012d38b/1204.jpg。

通过nginx配置想实现如下效果,首先访问本地目录查看是否存在该文件(/export/home/pic/sell/4f407ad7e588e535b012d38b/1204.jpg),存在则直接返回该图片;若不存在则转而访问远程图片服务http://192.168.1.12:80/sell/4f407ad7e588e535b012d38b/1204.jpg并返回。

我测试了try_files语法,但是始终没有成功,感觉问题点是远程图片服务没有配置对,配置如下:

---------------------------------------------------------------------------------------------------------

#适配URL示例:/sell/4f407ad7e588e535b012d38b/small_1204.jpg
location ~ /sell/(.*)/(.*)_(.*)\.(gif|jpg|jpeg|png|ico|JPG|GIF|PNG|JPEG)$ {
    set $type $2;
    set $h 64;#图片高
    set $w 64;#图片宽

    if ($type = "small") {
         set $h 120;
        set $w 120;
    }

    if ($type = "medium") {
        set $h 310;
        set $w 310;
    }

    #root /export/home/pic/;

    #image_filter_jpeg_quality 20;
    #根据给定的长宽生成缩略图
    image_filter resize $h $w;
    #原图最大2M,要裁剪的图片超过2M返回415错误,需要调节参数image_filter_buffer 
    #image_filter_buffer 10M;
    #image_filter_interlace on;
    #image_filter rotate 20;
    #image_filter crop 200 200;
    #image_filter size;
    #image_filter test;

    try_files @localpic
                @picserver
                @notfound ;

    #access_log off;
    #expires 7d;
}

location @localpic {
    if ( $uri ~ /sell/(.*)/(.*)_(.*)\.(gif|jpg|jpeg|png|ico|JPG|GIF|PNG|JPEG)$ ) {
        rewrite /sell/(.*)/(.*)_(.*)\.(gif|jpg|jpeg|png|ico|JPG|GIF|PNG|JPEG)$ /sell/$1/$3.$4;
    }
}

location @picserver {
    if ( $uri ~ /sell/(.*)/(.*)_(.*)\.(gif|jpg|jpeg|png|ico|JPG|GIF|PNG|JPEG)$ ) {
        proxy_pass   http://192.168.1.12:80/sell/$1/$3.$4;
    }
}

location ~ /sell/.*\.(gif|jpg|jpeg|png|ico|JPG|GIF|PNG|JPEG)$ {
    root /export/home/pic/;
}

location @notfound {
    empty_gif;
}

加载中
返回顶部
顶部