Nginx rewrite URL only if file exists

nginxrewrite

I need to write a rewrite rule for Nginx so that if a user tries to go to an old image url:

/images/path/to/image.png

and the file doesnt exist, try to redirect to:

/website_images/path/to/image.png

ONLY if the image exists in the new URL, otherwise continue with the 404. The version of Nginx on our host doesn't have try_files yet.

Best Answer

location /images/ {
    if (-f $request_filename) {
        break;
    }

    rewrite ^/images/(.*) /new_images/$1 permanent;
}

Though, you might want to bug your host to upgrade or find a better host.

Related Topic