Search code examples
nginxstatic-filesfallback

nginx static images fallback


i use nginx 1.6.2 to serve static images from a folder. I need to serve the requested file if exists or fallback to a default image.

i had this location block

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

The "/path/to/folder/images" folder contains 2 files: image1.jpg and default.jpg. If I request an existing image all works correctly. For example, if I do a GET on this url

<host_name>/test/img/image1.jpg

I can see the correct image but if I search an unknown image I had a 404 response. From the error.log file I can see this error:

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

Why nginx searchs default.jpg in that folder? I expected to search that file in the root of the location block. I tried without success to use the absolute path. Thanks in advance.


Solution

  • try_files last parameter leads to internal redirect. So nginx acts as if it was called with URI /default.jpg and will not go to /test/img/.

    But you problem could be fixed easily with alias directive without rewrites.

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

    testing config

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

    Requests:

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

    debug log:

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