我认为您可以通过多种方式实现这一目标。
选项 1:使用 Apache 的 PageSpeed 模块(又名mod_pagespeed):
PageSpeed 模块会优化您的图像以最小化它们的大小,从而减少它们的加载时间。它们去除不可见的图像信息并应用高效压缩技术。这可以节省 50% 或更多的数据。
使用 PageSpeed 模块,您可以专注于您网站的内容,知道您的访问者将在使用最小带宽的情况下收到适合其设备和浏览器的最佳格式和尺寸的图像。
https://www.modpagespeed.com/doc/filter-image-optimize
如何安装它的信息可以在in the official docs找到。
选项 #2:使用自定义图像压缩服务,并反向代理图像请求。
如果由于某种原因 Apache PageSpeed 模块无法工作,您可以设置反向代理缓存。 Nginx 将首先检查缓存,获取 MISS,然后在内部从压缩服务请求图像,然后返回压缩图像,同时将其保存到磁盘,以便下一个请求将命中缓存。
以下是设置的详细信息。
您将首先创建一个带有正则表达式的 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; # Cache HTTP 200 responses for up to 1 day.
# Keep using a stale cache during the short time it takes to refresh it (so
# we don't get a bunch of requests through # at the instant the cache becomes
# invalid).
# See: https://www.nginx.com/blog/mitigating-thundering-herd-problem-pbs-nginx/
proxy_cache_use_stale error timeout invalid_header updating
http_500 http_502 http_503 http_504;
# "Allows starting a background subrequest to update an expired cache item,
# while a stale cached response is returned to the client."
# See: https://www.nginx.com/blog/nginx-caching-guide/#proxy_cache_background_update
proxy_cache_background_update on;
最后,在http {...} 块中,设置我们上面命名的“images_cache”缓存:
proxy_cache_path
/tmp/nginx-cache
# Use a two-level cache directory structure, because the default
# (single directory) is said to lead to potential performance issues.
# Why that is default then... your guess is as good as mine.
levels=1:2
# A 10MB zone keeps ~80,000 keys in memory. This helps quickly determine
# if a request is a HIT or a MISS without having to go to disk.
keys_zone=images_cache:10m
# If something hasn't been used in quite a while (60 days), evict it.
inactive=60d
# Limit on total size of all cached files.
max_size=100m;
在您的自定义图像压缩服务(在上面的 example.com)中,您可能想要编写一个小服务(在 Node、Python、Rust 或其他中)获取传递给它的 URL,从磁盘位置(在 .../images/originals 或任何地方),压缩并返回它。我会把它留给读者:-)