【问题标题】:Nginx configuration proxy_pass with conditions based on image extensionNginx 配置 proxy_pass 与基于图像扩展的条件
【发布时间】:2020-08-12 07:07:47
【问题描述】:

我有一个调整大小的服务器映像,具有以下 nginx 配置:

  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;
  }

以下是浏览器访问时的URL https://test.org/100x100/upload/image.jpg。

我目前有 2 个图像大小调整服务器,1 个用于 jpg 和 1 个用于 png。如果为 jpeg 请求文件,我该如何制作,那么它将被定向到第一个代理通道,如果是 png,它将被定向到第二个代理通道。不删除宽度 ($1)、高度 ($2) 和文件夹 ($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;
      }
  }

请帮忙。

【问题讨论】:

  • 太棒了,谢谢@RichardSmith..
  • 如果我想添加扩展名 .jpeg,我必须更改为 ..../(.+\.(jpg|jpeg))$ ?

标签: variables nginx reverse-proxy image-resizing proxypass


【解决方案1】:

location 块中的正则表达式包含三个数字捕获,分配给 $1$2$3

最终捕获可以包含一个模式,该模式将匹配限制为以 .jpg.png 等结尾的 URI。

例如:

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

要匹配两个或多个文件扩展名,请使用交替组。例如:

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

最后一个示例创建了另一个分配给$4 的数字捕获,可以忽略它。可以使用非捕获组(例如(?:jpg|jpeg)),但它会使正则表达式难以阅读。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-31
    • 2017-08-25
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 2013-07-15
    相关资源
    最近更新 更多