2

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?

Vincent111
  • 21
  • 1
  • 2

2 Answers2

1

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.

mahemoff
  • 197
  • 11
0

I'm still not sure why but I needed to change the cache key.

proxy_cache_key "$host$request_uri";

Full block:

    location / {
        proxy_pass http://gitlab-pages;
        include proxy_params;

        more_set_input_headers  "Host: templates.pages.example.com";

        proxy_cache            gitlab;
        proxy_cache_key        "$host$request_uri";
        proxy_cache_use_stale  error timeout updating http_500 http_502 http_503 http_504 http_404;
        proxy_cache_lock       on;
        proxy_cache_valid      200 302 304 404 5m;
        proxy_cache_valid      any 1m;
        proxy_cache_revalidate on;
        proxy_ignore_headers   "Set-Cookie";
        proxy_hide_header      "Set-Cookie";

        add_header            X-CACHE $upstream_cache_status always;
    }
Kurt
  • 211
  • 2
  • 9