Nginx reverse proxy to CDN with automatically finds the right image size by configured array

Viewed 266

I have the following URL's on a CDN

https://storage.googleapis.com/my-bucket/1.png
https://storage.googleapis.com/my-bucket/1_50x50.png
https://storage.googleapis.com/my-bucket/1_150x150.png
https://storage.googleapis.com/my-bucket/1_300x300.png
https://storage.googleapis.com/my-bucket/1_500x500.png
https://storage.googleapis.com/my-bucket/1_1000x1000.png
https://storage.googleapis.com/my-bucket/1_3000x3000.png

I want Nginx to forward the following url, (because I have an external service which I can't edit that does these requests)

https://my-reverse-proxy.domain.com/my-bucket/1.png?width=350&height=350

to

https://storage.googleapis.com/my-bucket/1_500x500.png

So it should find to nearest number (higher or equal) in the CDN but if it is higher than 3000 it should return the original image.

Unfortunately we are not sure if the external services uses the exact same numbers as we have available, so the external service could send width=350 while we only have 300 or 500 images available.

I have no idea if this can be done in the Nginx config. Is this possible and how should it be done? I'm open to alternative solutions!

The width and height in the CDN are always the same, so looking at the width only would be fine!

1 Answers

The best option here would be to create rewrite rules in Nginx, and match your desired paths with regular expressions. Here, you can find a document describing the creation and usage of rewrite rules [1].

Here’s a sample NGINX rewrite rule that uses the rewrite directive. It matches URLs that begin with the string /download and then include the /media/ or /audio/ directory somewhere later in the path. It replaces those elements with /mp3/, and adds the appropriate file extension, .mp3 or .ra. The $1 and $2 variables capture the path elements that aren't changing. As an example, /download/cdn-west/media/file1 becomes /download/cdn-west/mp3/file1.mp3. If there is an extension on the filename (such as .flv), the expression strips it off and replaces it with .mp3:

server {
    # ...
    rewrite ^(/download/.*)/media/(\w+)\.?.*$ $1/mp3/$2.mp3 last;
    rewrite ^(/download/.*)/audio/(\w+)\.?.*$ $1/mp3/$2.ra  last;
    return  403;
    # ...
}

[1] https://www.nginx.com/blog/creating-nginx-rewrite-rules/

Related