Nginx Reverse Proxy with Thumbor for Efficient Image Cropping

nginx reverse proxythumbor image croppingcdn image optimizationnginx image filterstatic resource caching
Published·Modified·

Nginx provides a module --with-http_image_filter_module that supports image cropping. If you are using a single Nginx node, this is not a problem. However, if multiple Nginx nodes need to support image cropping, each node must be compiled with the --with-http_image_filter_module enabled. This module uses the GD library for cropping, and its performance is not ideal. We can completely use the higher-performance and more flexible Thumbor image cropping service to replace --with-http_image_filter_module.

Scenario

In xiaoz's scenario, there are multiple Nginx nodes acting as a CDN cluster to cache and accelerate static resources like images. When I access https://domain.com/123.jpg, I want to generate thumbnails by adding parameters. For example, if I want to crop a thumbnail of 200 * 150px, I just need to access https://domain.com/123.jpg/cut?w=200&h=150.

I used ProcessOn to draw a rough flowchart:

Preparation

Implementation

Add the following configuration to your Nginx reverse proxy configuration (within the server block):

# Image cropping
    location ~* /(.+)\.(jpg|gif|png|jpeg|webp|bmp)/cut {
    # Declare the full request address
    set $foo $scheme://$host/$1.$2;
    add_header XCDN-Cut 'success';
    # Ignore source server headers, force caching
    proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-Cookie Vary;
    
    proxy_connect_timeout 5;
    # Default is HTTP/1, keepalive is only enabled in HTTP/1.1
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    #chunked_transfer_encoding off;
    
    # Reverse proxy for image cropping
    proxy_pass http://192.168.123.4:8888/unsafe/${arg_w}x${arg_h}/$foo;
    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    ...
}

The above configuration matches image formats and uses Thumbor for cropping. Here is an explanation of the parameters:

  • set $foo $scheme://$host/$1.$2; This line retrieves the full image address (e.g., https://domain.com/123.jpg) and assigns it to the variable $foo.
  • add_header XCDN-Cut 'success'; Adds a custom response header field XCDN-Cut, making it easy to judge and debug.
  • In the proxy_pass directive, we request the Thumbor HTTP API for image cropping. Change http://192.168.123.4:8888/ to your own Thumbor address.

The above is only the most basic implementation. Specific rules should be adjusted according to actual circumstances, such as caching and anti-leech protection.

Summary

Through the above method, Nginx can be endowed with image cropping capabilities without additionally compiling the --with-http_image_filter_module module. In the case of multiple Nginx nodes, relying on Thumbor for centralized image cropping is simpler and more convenient.