nginx static images fallback -
i use nginx 1.6.2 serve static images folder. need serve requested file if exists or fallback default image.
i had 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 , default.jpg. if request existing image works correctly. example, if on url
<host_name>/test/img/image1.jpg
i can see correct image if search unknown image had 404 response. error.log file can see error:
[error] 18128#0: *1 open() "/etc/nginx/html/default.jpg" failed (2: no such file or directory)
why nginx searchs default.jpg in folder? expected search file in root of location block. tried without success use absolute path. in advance.
try_files
last parameter leads internal redirect. nginx acts if called uri /default.jpg
, not go /test/img/
.
but problem fixed 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:
... 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 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" ... 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 use file: "non-existent.jpg" "/var/tmp/site/images/non-existent.jpg" 2015/06/05 12:15:50 [debug] 4299#0: *4 trying 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"
Comments
Post a Comment