Nginx 仅在文件存在时重写 URL

Jos*_*dez 13 rewrite nginx

我需要为 Nginx 编写一个重写规则,以便如果用户尝试转到旧图像 url:

/images/path/to/image.png

并且文件不存在,尝试重定向到:

/website_images/path/to/image.png

仅当图像存在于新 URL 中时,否则继续 404。我们主机上的 Nginx 版本还没有 try_files。

Mar*_*ald 19

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

    rewrite ^/images/(.*) /new_images/$1 permanent;
}
Run Code Online (Sandbox Code Playgroud)

不过,您可能希望通过调试主机来升级或找到更好的主机。

  • @riverfall Heh,我写了该页面的一部分。我的答案是 8 年前写的,所以是的,它有点过时了,但最初的问题确实明确指出他们的主机没有提供最新版本的 nginx,因此他们无法访问 try_files。 (2认同)

Gar*_*orn 7

请不要if在位置块内使用。可能会发生不好的事情。

location ~* ^/images/(.+)$ {
    root /www;
    try_files /path/to/$1 /website_images/path_to/$1 /any/dir/$1 @your404;
}
Run Code Online (Sandbox Code Playgroud)

$1 成为要在 try_files 指令中尝试的文件名,该指令专为您要完成的任务而设计。

这,或者,只是重写它而不检查。如果该图像不存在,无论如何您都会收到 404。


小智 5

你可以使用这样的东西(针对你的具体情况未经测试):

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这基本上是编写嵌套if语句的另一种方式,因为您不能在 Nginx 中嵌套。有关此“黑客”的官方参考,请参见此处