4

I have a directory of images at /img/. When a request is made to an image in that directory that does not exist, I would like to serve /img/default.jpg. How would I add this to my nginx configuration?

1 Answer 1

8

Do this:

location /img {
  try_files $uri /img/default.jpg;
}

That will not redirect the request to default.jpg, but instead the file contents of their request will be served with the default.jpg contents instead.

More info here: http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

Redirecting would be pretty messy and would need to make use of the if directive. You can do that too though. More info here: http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#if

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.