配置图片裁剪,首先需要 Image Filter module(图像过滤处理模块)
即我们在编译安装nginx的时候,需要指定该模块
./configure --prefix=/usr/lib/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log \ --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --user=nginx --group=nginx \ --with-http_ssl_module --with-http_image_filter_module --with-http_flv_module --with-http_stub_status_module --with-http_gzip_static_module
接下来要去/etc/nginx/nginx.conf配置它:
http {
server {
listen 5000;
server_name localhost;
# 这里我们的主要逻辑代码运行在10000端口,路由以版本号/v1开头,作代理访问
location ~ ^/v1/* {
proxy_pass http://127.0.0.1:10000;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_redirect off;
}
# 将图片服务转发到其他端口
location /_images/{
proxy_pass http://127.0.0.1:5001/;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_redirect off;
}
}
server {
listen 5001;
server_name localhost;
# 将图片裁剪服务转发到30006端口
location ~ /images/(.*)\.(ico|gif|jpg|jpeg|png)$ {
proxy_pass http://127.0.0.1:30006/images/$1.$2?$args;
}
# 下面两条是开放资源给前端访问的,前端只需传:192.168.1.1:5000/_images/111/s.mp4
location ~* \.(mp4|flv|avi)$ {
root /data/new_video;
}
location ~* \.(jpg|png|jpeg)$ {
root /data/image;
}
}
server {
listen 30006;
server_name localhost;
root /data/image;
location /favicon.ico {
log_not_found off;
access_log off;
}
location ~ /image_resize/(\d+)_(\d+)/(.*)\.(ico|gif|jpg|jpeg|png)$ {
alias /data/image/$3.$4;
image_filter resize $1 $2;
image_filter_jpeg_quality 85; # jpeg图片质量.
image_filter_buffer 30M; # 这里需要手动设置下图片缓存大小,默认为1M,超出1M的图片服务器会报错。
image_filter_interlace on; # 将jpeg图片转换为可以渐进式加载的格式,这样用户可以尽快看到图片效果
image_filter_transparency on; # 是否保留图片的透明像素,因为我们还有png图,所以这里要打开
}
location ~ /images/(\d+)_(\d+)/(.*)\.(ico|gif|jpg|jpeg|png)$ {
set $wd $1;
set $hd $2;
set $file_path $3.$4;
# 限制裁剪图片宽和高
if ($wd !~ "^(900|400)") {
return 403;
}
if ($hd !~ "^(500|200)") {
return 403;
}
expires 5d;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_cache images;
proxy_cache_key $uri;
proxy_cache_valid 200 301 302 304 5d;
proxy_cache_valid any 1m;
proxy_pass http://127.0.0.1:30006/image_resize/${wd}_$hd/$file_path?$args;
}
}
}