Nginx - 如果 'alias' 失败,则将请求转发到服务器应用程序

Nginx - Forwarding a request to the Server-App if 'alias' fails

对于一个项目,我实现了自动服务器端缩略图生成。如果您请求文件名中带有“_thumb”的图像,服务器会检查是否已经存在原始图像的缩略图,如果没有,则生成缩略图并将其发回。工作正常。

现在我想将 Nginx 加入到组合中以直接从硬盘驱动器提供图像而不涉及服务器应用程序(url 本身可以正常工作并且 return 如果图像从服务器应用程序本身请求)。

如果缩略图已经存在,则以下块可以正常工作。如果还没有生成缩略图,它只会响应 404 - 不出所料。

如果找不到缩略图来创建缩略图,我将如何修改以下 Nginx-Block 以向服务器发出另一个请求?

请求

http://www.proj.com/files/images/234782348234/bunny_thumb.jpg

Nginx 块

location ~* ^/files/images/(\w+)/.+_thumb\.(jpg|png|gif)$ {
   alias /srv/proj/data/uploads/images/temp/_thumb.;
   // No image found? Request it from the server directly on "files/images/234782348234/bunny_thumb.jpg"
}

实际文件路径

/srv/proj/data/uploads/images/temp/234782348234_thumb.jpg

有时候看看nginx公司的优秀博客会有帮助

您搜索的名称为 try_files 的命名位置。

https://www.nginx.com/resources/admin-guide/nginx-web-server/

https://www.nginx.com/resources/admin-guide/serving-static-content/

location / {
    try_files $uri $uri/ @backend;
}

location @backend {
    proxy_pass http://backend.example.com;
}

对于你的情况,我会尝试以下方法

location ~* ^/files/images/(\w+)/.+_thumb\.(jpg|png|gif)$ {
   try_files /srv/proj/data/uploads/images/temp/_thumb. @callapp;
   // No image found? Request it from the server directly
   // on "files/images/234782348234/bunny_thumb.jpg"
}

location @callapp {
...
}

所以,最后不得不再次解决它并找到了一个非常简单的解决方案。 RegexMatches 仍然无法在 try_files 中使用。所以我只是使用 "alias" 指向实际的文件路径并定义了一个 'error_page 404' 指向 expressapp:

location ~* ^/files/images/(\w+)/.+_thumb\.(jpg|png|gif)$ {
   error_page 404 @makethumb
   alias /srv/proj/data/uploads/images/temp/_thumb.;
 }

location @makethumb {
    proxy_pass http://localhost:3000$uri;
}