Weserv Images#

weserv 模块用于即时调整图像大小、裁剪和转换格式。它是 weserv/images 项目的一部分,该项目是 wsrv.nl 服务背后的代码。该模块有两种工作模式:

  • proxy — 从 url 查询参数给出的远程服务器获取图像;

  • filter — 处理其他处理程序(如静态文件)所生成响应中的图像。

在这两种模式下,处理方式均由查询字符串设定:w 和 h 设置目标宽度和高度,fit 设置图像如何适应该尺寸,output 设置输出格式,等等。完整的参数列表见 wsrv.nl 文档。

安装#

要 安装 该模块,请使用以下软件包之一:

  • Angie:angie-module-weserv-images

  • Angie PRO:angie-pro-module-weserv-images

指令#

该模块的主要指令:

  • weserv — 在 location 中启用该模块并选择模式,proxy 或 filter

  • weserv_deny_ip — 禁止从指定的地址或 CIDR 范围获取图像;它仅适用于 url 参数中直接写出的 IP 地址,不适用于主机名

  • weserv_connect_timeout、weserv_send_timeout、weserv_read_timeout — 分别设置连接远程服务器、向其发送请求以及读取其响应的超时时间

  • weserv_max_size — 限制待处理图像的大小

  • weserv_limit_input_pixels、weserv_limit_output_pixels — 限制输入和输出图像的像素数

  • weserv_savers — 列出 output 参数可请求的输出格式

  • weserv_quality — 设置默认的输出质量;weserv_jpeg_quality 和 weserv_webp_quality 等指令可为单一格式覆盖该值

在 proxy 模式下,$weserv_response_length 变量保存所获取原始图像的大小(以字节为单位);在 filter 模式下,不设置该变量。

所有指令及其默认值均在模块文档 中说明。

加载模块#

要使用该模块,必须在 main{} 上下文中加载它:

load_module modules/ngx_weserv_module.so;

配置示例#

server {
    listen 80;

    server_name images.weserv.local;

    root /var/www/imagesweserv/public;

    location / {
        weserv proxy;

        add_header X-Upstream-Response-Length $weserv_response_length;
    }

    location /static/ {
        weserv filter;

        alias /var/www/imagesweserv/public/;
    }
}

在此配置中,带有 url 参数的请求以 proxy 模式处理,而对于 /static/ 下的请求,模块以 filter 模式处理 /var/www/imagesweserv/public/ 目录中的文件。对 / 的不带 url 的请求不由该模块处理,而是从 root 返回静态文件。

Angie 使用自己的解析器解析 url 中的主机名;默认情况下,它会查询 /etc/resolv.conf 中列出的名称服务器,而不会查询 /etc/hosts 文件。要使用其他 DNS 服务器,请设置 resolver 指令。url 中的 IP 地址无需解析。

演示#

假设 127.0.0.1:8081 上的服务器提供原始图像 sample.png(400 × 300 像素,2351 字节),并且同一文件也位于 /var/www/imagesweserv/public/ 中。

在 proxy 模式下,模块获取 url 中给出的图像,并将其缩放到宽度 w,同时保持纵横比:

$ curl -s -D - -o out.png 'http://localhost/?url=127.0.0.1:8081/sample.png&w=100'
HTTP/1.1 200 OK
...
Content-Type: image/png
Content-Length: 15633
Content-Disposition: inline; filename=image.png
Link: <http://127.0.0.1:8081/sample.png>; rel="canonical"
...
X-Upstream-Response-Length: 2351

$ file out.png
out.png: PNG image data, 100 x 75, 8-bit/color RGB, non-interlaced

Link 头指向原始图像,X-Upstream-Response-Length 携带其大小,示例配置通过 $weserv_response_length 添加了该头。url 中的 http:// 前缀是可选的;在同一请求中添加 &output=jpg 则返回 JPEG 图像。

在 filter 模式下,相同的参数适用于本地文件;这里将图像裁剪以填满 50 × 50 的正方形,并转换为 WebP:

$ curl -s -D - -o small.webp 'http://localhost/static/sample.png?w=50&h=50&fit=cover&output=webp'
HTTP/1.1 200 OK
...
Content-Type: image/webp
Content-Length: 250
...

文件 small.webp 是 50 × 50 的 WebP 图像。响应中没有 X-Upstream-Response-Length 头:/static/ location 不添加该头,而且在 filter 模式下 $weserv_response_length 未设置。

当模块无法返回图像时,它会以 JSON 格式返回错误:

$ curl -s 'http://localhost/?url=127.0.0.1:8081/missing.png'
{"status":"error","code":404,"message":"The requested URL returned error: 404"}

附加信息#

版本: v5.1.0

详细文档和源代码可在以下位置获取: weserv/images