我需要为Nginx编写一个重写规则,以便如果用户尝试去旧的图像url:
/images/path/to/image.png
和该文件不存在,请尝试redirect到:
/website_images/path/to/image.png
只有图像存在于新的URL中,否则继续404。我们的主机上的Nginx版本还没有try_files。
location /images/ { if (-f $request_filename) { break; } rewrite ^/images/(.*) /new_images/$1 permanent; }
虽然,你可能想要bug你的主机升级或find一个更好的主机。
你可以使用这样的东西(未经testing你的具体情况):
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; } }
这基本上是编写嵌套的if语句的另一种方式,因为你不能嵌套在Nginx中。 在这里看到这个“黑客”的官方参考。
if在一个位置块内,请不要使用。 坏事可能会发生。
location ~* ^/images/(.+)$ { root /www; try_files /path/to/$1 /website_images/path_to/$1 /any/dir/$1 @your404; }
$1成为在try_files指令中尝试的文件名,这个指令是为你想要完成的。
这个,或者,只是重写它没有检查。 如果这个图像不在那里,反正你会得到一个404。