Search code examples
variablesnginxreverse-proxyimage-resizingproxypass

Nginx configuration proxy_pass with conditions based on image extension


I have a resized server image with the following nginx configuration:

  location ~ ^/assets/([0-9]+)x([0-9]+)/(.+) {
       proxy_pass http://192.168.0.15:9900/fit?width=$1&height=$2&interlace=true&url=https://cdn.test.org/assets/$3;
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-FRAME-OPTIONS SAMEORIGIN;
       proxy_set_header X-Forwarded-For $remote_addr;
  }

and the following is the URL when accessed in the browserhttps://test.org/100x100/upload/image.jpg.

and I currently have 2 images resize servers, 1 for jpg and 1 for png. how can I make if the file is requested for jpeg, then it will be directed to the first proxy pass, and if png it will be directed to the second proxy pass. without removing the variable values for the width ($1), height ($2) and the folder after ($3).

  location ~ ^/assets/([0-9]+)x([0-9]+)/(.+) {
           proxy_pass http://192.168.0.15:9900/fit?width=$1&height=$2&interlace=true&url=https://cdn.test.org/assets/$3;
           proxy_set_header Host $host;
           proxy_set_header X-Real-IP $remote_addr;
           proxy_set_header X-FRAME-OPTIONS SAMEORIGIN;
           proxy_set_header X-Forwarded-For $remote_addr;
      location ~ ^/assets/$1x$2/$3\.png$ {
                proxy_pass http://192.168.0.20:9900/fit?width=$1&height=$2&quality=90&interlace=true&url=https://cdn2.test.org/$3;
      }
  }

Please help.


Solution

  • The regular expression in your location blocks contain three numeric captures, assigned to $1, $2 and $3.

    The final capture can contain a pattern that restricts matches to URIs which end with .jpg or .png etc.

    For example:

    location ~ ^/assets/([0-9]+)x([0-9]+)/(.+\.png)$ { ... }
    

    To match two or more file extensions, use an alternation group. For example:

    location ~ ^/assets/([0-9]+)x([0-9]+)/(.+\.(jpg|jpeg))$ { ... }
    

    This last example creates another numeric capture assigned to $4 which can be ignored. It is possible to use non-capturing groups (e.g. (?:jpg|jpeg)) but it can make the regular expression difficult to read.