【问题标题】:nginx static images fallbacknginx 静态图片后备
【发布时间】:2015-08-19 07:47:37
【问题描述】:

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

我有这个位置块

location /test/img/ {
    rewrite  ^/test/img/(.*)  /$1 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?我希望在 location 块的根目录中搜索该文件。我尝试使用绝对路径但没有成功。 提前致谢。

【问题讨论】:

    标签: nginx static-files fallback


    【解决方案1】:

    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"
    

    【讨论】:

    • 我尝试了您的解决方案,但它不起作用。如果我将 default.jpg 替换为 /default.jpg 它会起作用。这是正确的吗?
    • 这很奇怪。我已经检查过我的 nginx。
    • 好的,你是对的...我没有在别名中添加斜杠。昨天我使用 root 和 rewrite 发布了解决方案...但是您的答案更优雅,客观...
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      • 1970-01-01
      • 2017-10-15
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      相关资源
      最近更新 更多