Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 7 down vote accepted
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.

share|improve this answer
    
This will redirect to /new_images on every 404 right? I don't want to do the rewrite unless I know the new_images file exists –  Jose Fernandez Mar 16 '10 at 13:58
    
This checks to see if the file exists, and if that test fails, it redirects to new_images. What happens after that is not specified here. –  tylerl Jul 31 '10 at 7:58

You could use something like this (untested for your specific case):

location ^/images/(?<imgpath>.*)$ {

    set $no_old  0;
    set $yes_new 0;

    if (!-f $request_filename)
    {
        set $no_old 1;
    }

    if (-f ~* "^/new_path/$imgpath")
    {
        set $yes_new 1$no_old;
    }

    # replacement exists in the new path
    if ($yes_new = 11)
    {
        rewrite ^/images/(.*)$ /new_path/$1 permanent;
    }

    # no image in the new path!
    if ($yes_new = 01)
    {
        return 404;
    }
}

Which is basically an alternative way of writing nested if statements, since you cannot nest in Nginx. See here for official reference on this "hack".

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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