我认为您可以通过以下几种方式实现。
选项1:使用Apache的PageSpeed模块(也称为
mod_pagespeed
):
PageSpeed模块优化图像,使它们的大小最小化,从而减少它们的加载时间。它们移除不可见的图像信息并应用高效的压缩技术。这可以节省50%或更多的数据。
使用PageSpeed模块,您可以专注于网站的内容,知道您的访问者将在使用最小带宽的同时,以最佳格式和尺寸接收图像。
https://www.modpagespeed.com/doc/filter-image-optimize
安装信息可以在官方文档中找到。
选项 #2:使用自定义图像压缩服务,并将图像请求反向代理到该服务。
如果 Apache PageSpeed 模块无法正常工作,您可以设置一个反向代理缓存。Nginx 首先检查缓存,获取MISS,然后从压缩服务内部请求图像,返回压缩的图像,同时将其保存到磁盘上,以便下一次请求会HIT缓存。
详细设置如下。
首先,您需要创建一个location { ... }
块,其中包含nginx在获取原始图像请求时匹配的正则表达式。
server {
# your standard nginx server stuff here, then:
# when reverse proxying, nginx needs a DNS resovler defined
# you may be able to skip this if you use an IP address instead of
# example.com below.
resolver 1.1.1.1 1.0.0.1 valid=300s;
resolver_timeout 2s;
location ~ ^/your/image/originals/(.*) {
proxy_ssl_server_name on;
proxy_pass https://www.example.com/your-custom-compression-service/$1;
# plus we need to define some extra stuff for caching; which I put
# in another file for modularity or reuse if later needed.
include "/absolute/path/to/nginx-includes/location-cache.config";
}
}
在您的“location-cache.config”文件中(可以命名为任何名称),您需要为缓存起一个名字,我们称其为“images_cache”:
proxy_cache images_cache;
proxy_cache_valid 200 1d;
proxy_cache_use_stale error timeout invalid_header updating
http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
最后,在
http {...}
块中,您设置了我们上面命名的“images_cache”缓存:
proxy_cache_path
/tmp/nginx-cache
levels=1:2
keys_zone=images_cache:10m
inactive=60d
max_size=100m;
在您的自定义图像压缩服务(如上例example.com)中,您可能需要编写一个小型服务(使用Node、Python、Rust或其他语言),该服务获取传递给它的URL,从磁盘位置(例如.../images/originals)获取URL,压缩并返回它。我将留给读者自行处理 :-)