kiran
kiran

Reputation: 23

Nginx rule for redirecting all image files

I am new to nginx. I want to redirect the fake image path of an website to original image path. For example assume that I have so many images on example.com home directory such as example.com/a.jpeg, example.com/b.png and example.com/c.jpg. If any one calls example.com/tests/a.jpeg, then it should redirect to example.com/a.jpeg.

So I want to write a rewrite rule for redirecting image files to original location.

Upvotes: 1

Views: 1095

Answers (1)

Richard Smith
Richard Smith

Reputation: 49742

So an image file within any directory of the hierarchy should actually be found at the top of the document root. So the URI /path/to/image.jpeg is mapped to the physical location $document_root/image.jpeg.

This is easily achieved with a regex location combined with try_files:

root /path/to/document/root;

location ~* ([^/]+\.(?:png|jpeg|jpg))$ {
    try_files /$1 =404;
}

Upvotes: 1

Related Questions