H
H
Hecktosaurus2021-05-25 16:48:46
Nginx
Hecktosaurus, 2021-05-25 16:48:46

Is it possible to chain execute php in nginx?

Hello! I need to convert pictures to webp, I do it with my own script. The problem is that in some cases the sources do not exist and they are generated on the fly by another script.

I would somehow set a condition by which it would be checked if the file exists by the query string - execute one script, if it does not exist - execute another accordingly.

I tried to implement it with such a construction, but it seems that the control always goes to the last script ( @shop_thumb ), and it doesn’t reach the main one ( @webp_gen ).

# рулим правилами для преобразования
location ~* ^.+\.(jpe?g|png)$ {
    types {
        image/jpeg jpeg jpg;
        image/png png;
        image/webp webp;
    }
    error_page   404  =  @shop_thumb;
    expires 365d;
    try_files  $uri.webp @webp_gen @shop_thumb;
}
# локейшн для конвертирования
# по идее, если сорца не существует, webp-converter.php отдаст 404 и управление уйдёт в @shop_thumb
location @webp_gen {
    error_page   404  =  @shop_thumb;
    include /etc/nginx/fastcgi_params;
    fastcgi_pass unix:/run/php/php7.2-fpm-ers.sock;
    fastcgi_param  SCRIPT_NAME  /webp/webp-converter.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root/webp/webp-converter.php;
}
# локейшн для генерации и сохранения сорца. Должен отрабатывать только тогда,
# когда $request_uri не существует.
# А затем, после повторного обращения, уже должно срабатывать @webp_gen
location @shop_thumb {
    include /etc/nginx/fastcgi_params;
    fastcgi_pass unix:/run/php/php7.2-fpm-ers.sock;
    fastcgi_param  SCRIPT_NAME  /products/thumb.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root/products/thumb.php;
}


And here is a part of the webp-converter.php code - if something goes wrong, a 404 is returned:
$docRoot = rtrim($_SERVER["DOCUMENT_ROOT"], '/');
$requestUriNoQS = explode('?', $_SERVER['REQUEST_URI'])[0];
$relativeSrcPath = urldecode($requestUriNoQS);
$source = $docRoot . $relativeSrcPath; 

if (!file_exists($source)){
  // нужно записать в лог и крешнуться
  if ($debugmode){
    writeLog('Нет файла "'.$source.'"');
  }
  header("HTTP/1.0 404 Not Found");
  exit;
}


Can you suggest what I'm doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2021-05-25
@Hecktosaurus

# по идее, если сорца не существует, webp-converter.php отдаст 404 и управление уйдёт в @shop_thumb
location @webp_gen {
    error_page   404  =  @shop_thumb;

To error_pageprocess response codes from fastcgi, you need to explicitly enable this with the fastcgi_intercept_errors directive .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question