NGINX How to redirect request to PHP-FPM if * .png is not found?

Question:

Tell me how to redirect a request to PHP-FPM in Nginx if a file with the * .png extension is not found? My file is generated "on the fly" by a script. NGINX does not pass such a request and returns a 404 response. I need the URL to end with the * .png extension.

Update

worker_processes  1;
events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;
    charset utf-8;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #root /var/www/example.com/web;

    server {
      listen      80 default_server;
      server_name "";
      rewrite     ^(.*)$ http://example.com/ permanent;
    }
    server {
        listen       192.168.6.58:80;
        server_name  example.com;
        root /var/www/protrader.org/web;

        charset utf-8;
        client_max_body_size 200m;


        #access_log  logs/host.access.log  main;

        location / {
            index  index.php index.html index.htm;
            try_files $uri $uri/ /index.php$is_args$args;
            location ~\.php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_param SCRIPT_FILENAME $request_filename;
            include fastcgi_params;
            }
        }

    location ~* ^.+\.(rss|atom|jpg|jpeg|gif|png|ico|rtf|js|css|svg|woff)$ {
        expires max;
    }

}

Answer:

Remove png from the list of extensions in this location: location ~* ^.+\.(rss|atom|jpg|jpeg|gif|png|ico|rtf|js|css|svg|woff)$ .

Add a separate location for it and in it add the error_page directive, which, with a 404 response, will lead to a named location with a name, for example, not_found.

In this location, redirect to 127.0.0.1:9000.

In total, you should have the following configuration:

server {
    listen       192.168.6.58:80;
    server_name  example.com;
    root /var/www/protrader.org/web;

    charset utf-8;
    client_max_body_size 200m;


    #access_log  logs/host.access.log  main;

    location / {
        index  index.php index.html index.htm;
        try_files $uri $uri/ /index.php$is_args$args;
        location ~\.php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_param SCRIPT_FILENAME $request_filename;
            include fastcgi_params;
        }
    }

    location ~* ^.+\.(rss|atom|jpg|jpeg|gif|ico|rtf|js|css|svg|woff)$ {
        expires max;
    }

    location @not_found {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        include fastcgi_params;
    }

    location ~* \.png$ {
        error_page 404 = @not_found;
    }
}
Scroll to Top