nginx 静态图像回退

nginx static images fallback

我使用 nginx 1.6.2 从文件夹提供静态图像。我需要提供请求的文件(如果存在)或回退到默认图像。

我有这个位置块

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

“/path/to/folder/images”文件夹包含 2 个文件:image1.jpg 和 default.jpg。 如果我请求现有图像,一切正常。例如,如果我在 url

上执行 GET
<host_name>/test/img/image1.jpg

我可以看到正确的图像,但如果我搜索未知图像,我会收到 404 响应。 从 error.log 文件我可以看到这个错误:

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

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

我找到了解决方案。 如果在根文件夹中找到 none 个文件,nginx 会重定向到 url 对应于 try_files 指令的最后一个参数。 所以正确的方块是

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

try_files 最后一个参数导致内部重定向。所以 nginx 的行为就好像它是用 URI /default.jpg 调用的一样,不会转到 /test/img/.

但是您的问题可以通过 alias 指令轻松解决,无需重写。

location /test/img/ {
    alias /path/to/folder/images/;
    try_files $uri default.jpg =404;
}

测试配置

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

请求:

curl localhost:8888/test/img/image.jpg
curl localhost:8888/test/img/non-existent.jpg

调试日志:

... 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"