在Nginx中实现图片代理和动态缩放可以通过以下几种方式:
这是Nginx官方提供的解决方案,需要在编译Nginx时加入--with-http_image_filter_module
。
配置示例:
server {
listen 80;
server_name example.com;
location /images/ {
# 原始图片路径
root /path/to/original/images;
}
location ~* /resize/(\d+)x(\d+)/(.*) {
# 代理到原始图片
proxy_pass http://127.0.0.1/images/$3;
# 开启图片处理
image_filter resize $1 $2;
image_filter_jpeg_quality 85;
image_filter_buffer 10M;
# 缓存处理后的图片
image_filter_cache 30d;
}
}
这种方法更灵活但需要额外安装组件:
配置示例:
location ~* ^/resize/(\d+)x(\d+)/(.*) {
set $width $1;
set $height $2;
set $image_path $3;
content_by_lua '
local gm = require "graphicsmagick"
local image = gm.new_image(ngx.var.image_path)
image:resize(tonumber(ngx.var.width), tonumber(ngx.var.height))
image:set_format("jpg")
ngx.header["Content-type"] = "image/jpeg"
ngx.print(image:to_blob())
';
}
这个模块专门用于图片缩略图生成:
location ~* /images/(.*)_(\d+)x(\d+)\.(jpg|png|gif)$ {
set $width $2;
set $height $3;
set $image $1.$4;
image_thumb on;
image_thumb_width $width;
image_thumb_height $height;
image_thumb_output_interlace on;
root /path/to/images;
}
可以配置Nginx将请求代理到专门的图片处理服务如Thumbor或imgproxy:
location ~* /resize/(\d+)x(\d+)/(.*) {
proxy_pass http://thumbor-server/$1x$2/$3;
proxy_set_header Host $host;
proxy_cache my_cache;
proxy_cache_valid 200 30d;
}
选择哪种方案取决于您的具体需求、流量规模和服务器资源。对于高流量站点,推荐使用专门的图片处理服务或CDN解决方案。