Home > OS >  How to Cache with NGINX a Location if link backend proxy_pass is dynamic with $arg_url
How to Cache with NGINX a Location if link backend proxy_pass is dynamic with $arg_url

Time:08-26

Hey Guys maybe can help me out, I am trying to cache an Image which every 5 minutes has a timestamp update in the path so it will always give a MISS after 5 minutes even if set to expire after 1h for example.

This is the Request URL: http://example.com//imagecache/?ts=1660906289182&url=http://website.com/image.jpg

Here the "ts=..." is changing every 5 minutes

Here is the nginx config:

    location = /imagecache/ {
           proxy_cache my_cache;
           proxy_cache_revalidate on;
           proxy_cache_min_uses 1;
           proxy_cache_lock on;
           proxy_cache_lock_timeout 5s;
           proxy_set_header Host $host;
           proxy_cache_key $request_uri;
           proxy_cache_valid 200 304 30m;
           proxy_cache_valid 302 301 2h;
           proxy_cache_valid any 5m;
           proxy_ignore_headers Cache-Control Expires Set-Cookie;
           proxy_cache_methods GET HEAD POST;
           proxy_cache_background_update on;
           proxy_cache_use_stale error timeout invalid_header http_403 http_404 http_429 http_500 http_502 http_503 http_504;
           add_header X-Cache-Status $upstream_cache_status;
           add_header X-Cache-Date $upstream_http_date;
           proxy_pass http://${BACKEND_HOSTNAME}:8080/html/mock/imageload.jsp?url=$arg_url;

I did try with reqrite but somehow was not working.

What I need is to ignore the ?ts=& and always see it as the same image and cache it in so like this the proxy_cache_valid time is used as it should.

The timestamp is changing but the image is the same.

Thanks for the help in advance.

CodePudding user response:

You can set your proxy_cache_key to exclude the ts query param and only include arg_url using http://nginx.org/en/docs/http/ngx_http_core_module.html#var_arg_

proxy_cache_key $scheme://$proxy_host$uri$is_args$arg_url;

If you have multiple query params you want to include and only exclude ts, you can create a map that regexes that query param out and then use it in your proxy_cache_key.

  • Related