Back
Featured image of post How to Resize Image on the fly with NGINX

How to Resize Image on the fly with NGINX

an alternative to Cloudflare edge 'Image Resizing' or just an easy way to get your image resized.

Maybe you’re someone who doesn’t have Cloudflare Pro and wants to resize image on the fly, well there’s an easy way for you to do so. NGINX has a feature called Image resize which is really useful for resizing image on the getgo.

Resizing Server configuration

Place this config inside your server block.

location ~ "^/(?<image>.+)@(?<width>\d+)$" {
    # The file root location of your website
    alias /var/www/static/$image;
    
    image_filter resize $width -;
    image_filter_sharpen 95;
    image_filter_buffer 25M;
}

image_filter

The module that we’re using to resize the image, you can read more options here nginx.org/en/docs/http/ngx_http_image_filter_module.html#image_filter

image_filter_sharpen

Sets the desired quality of the transformed JPEG images. Acceptable values are in the range from 1 to 100. Lesser values usually imply both lower image quality and less data to transfer. The maximum recommended value is 95. Parameter value can contain variables.

image_filter_buffer

Sets the maximum size of the buffer used for reading images. When the size is exceeded the server returns error 415 (Unsupported Media Type).

Here are some example of NGINX on fly resize in action:

ps open the image in a new tab to see the difference

Original 3648 x 3246

cdn.darrennathanael.com/assets/unsplash/jack-antal-794153-unsplash.jpg
cdn.darrennathanael.com/assets/unsplash/jack-antal-794153-unsplash.jpg

1080 x 960

cdn.darrennathanael.com/assets/unsplash/jack-antal-794153-unsplash.jpg@1080
cdn.darrennathanael.com/assets/unsplash/jack-antal-794153-unsplash.jpg@1080

420 x 373

cdn.darrennathanael.com/assets/unsplash/jack-antal-794153-unsplash.jpg@420
cdn.darrennathanael.com/assets/unsplash/jack-antal-794153-unsplash.jpg@420

May your USB connectors always be facing the right way.
Theme designed Jimmy.

AbuseIPDB Contributor Badge DMCA.com Protection Status