nginx静态图像后备

cod*_*upo 1 fallback nginx static-files

我使用nginx 1.6.2来提供文件夹中的静态图像.如果存在或回退到默认图像,我需要提供所请求的文件.

我有这个位置块

location /test/img/ {
    rewrite  ^/test/img/(.*)  /$1 break;
    root   /path/to/folder/images;
    try_files $uri /default.jpg;
}
Run Code Online (Sandbox Code Playgroud)

"/ path/to/folder/images"文件夹包含2个文件:image1.jpg和default.jpg.如果我请求现有图像,则一切正常.例如,如果我在这个网址上进行GET

<host_name>/test/img/image1.jpg
Run Code Online (Sandbox Code Playgroud)

我可以看到正确的图像,但如果我搜索未知图像,我有404响应.从error.log文件中我可以看到此错误:

[error] 18128#0: *1 open() "/etc/nginx/html/default.jpg" failed (2: No such file or directory)
Run Code Online (Sandbox Code Playgroud)

为什么nginx在该文件夹中搜索default.jpg?我希望在位置块的根目录中搜索该文件.我尝试使用绝对路径没有成功.提前致谢.

Ale*_*Ten 5

try_files最后一个参数导致内部重定向.所以nginx就好像用URI调用一样,/default.jpg不会去/test/img/.

但是您可以使用alias指令轻松修复问题而无需重写.

location /test/img/ {
    alias /path/to/folder/images/;
    try_files $uri default.jpg =404;
}
Run Code Online (Sandbox Code Playgroud)

测试配置

server {
    listen 127.0.0.1:8888;
    location /test/img/ {
        alias /var/tmp/site/images/;
        try_files $uri default.jpg =404;
        error_log /var/log/nginx/error.log debug;
    }
}
Run Code Online (Sandbox Code Playgroud)

要求:

curl localhost:8888/test/img/image.jpg
curl localhost:8888/test/img/non-existent.jpg
Run Code Online (Sandbox Code Playgroud)

调试日志:

... for image.jpg
2015/06/05 12:16:53 [debug] 4299#0: *5 try files phase: 14
2015/06/05 12:16:53 [debug] 4299#0: *5 http script var: "/test/img/image.jpg"
2015/06/05 12:16:53 [debug] 4299#0: *5 trying to use file: "image.jpg" "/var/tmp/site/images/image.jpg"
2015/06/05 12:16:53 [debug] 4299#0: *5 try file uri: "/test/img/image.jpg"

... for non-existent.jpg
2015/06/05 12:15:50 [debug] 4299#0: *4 try files phase: 14
2015/06/05 12:15:50 [debug] 4299#0: *4 http script var: "/test/img/non-existent.jpg"
2015/06/05 12:15:50 [debug] 4299#0: *4 trying to use file: "non-existent.jpg" "/var/tmp/site/images/non-existent.jpg"
2015/06/05 12:15:50 [debug] 4299#0: *4 trying to use file: "default.jpg" "/var/tmp/site/images/default.jpg"
2015/06/05 12:15:50 [debug] 4299#0: *4 try file uri: "/test/img/default.jpg"
Run Code Online (Sandbox Code Playgroud)