Nginx Cache even if it's a 404 response

I use 404 rewriting url:

    error_page 404 = /url_rewriting.php;

I cache images generated with a render script being in a folder /render/:

    set $no_cache 0;

    location ~ /render/ {
            include snippets/fastcgi-php.conf;
            #fastcgi_pass unix:/run/php/php7.0-fpm.sock;
            fastcgi_pass 127.0.0.1:9000;

            fastcgi_buffers 8 16k; # increase the buffer size for PHP-FTP
            fastcgi_buffer_size 32k; # increase the buffer size for PHP-FTP
            fastcgi_cache_key $scheme$host$request_uri$request_method;
            fastcgi_cache PROD;
            fastcgi_cache_valid any 20d;
            fastcgi_cache_valid 404      1d;
            fastcgi_cache_use_stale updating error timeout invalid_header http_500 http_503;
            fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
            fastcgi_hide_header "Set-Cookie";
            fastcgi_cache_bypass $no_cache;
            fastcgi_no_cache $no_cache;
            expires 10M;
            access_log off;
            add_header Cache-Control "public";
            add_header X-Cache-Status $upstream_cache_status;
    }

The cache works with an url like this:

https://mywebsite.com/include/php/render/framed/img.php?VR=1&size=300&image=U3pmwKi

But the cache does not work with an url like this:

https://mywebsite.io/include/php/render/framed/file/VR/1/size/300/image/U3dpwK

This second URL go through error_page 404 = /url_rewriting.php; because the directory 'file' does not exists but the script display the image thanks to url_rewriting.php script which do the trick

What do I have to update to my Nginx config to be able to cache 404 responses?


Caching error responses is possible with the always keyword:

add_header Cache-Control "public; max-age=3600" always;

From the docs:

Adds the specified field to a response header provided that the response code equals 200, 201 (1.3.10), 204, 206, 301, 302, 303, 304, 307 (1.1.16, 1.0.13), or 308 (1.13.0) ... If the always parameter is specified (1.7.5), the header field will be added regardless of the response code.