Last active
December 2, 2022 21:04
-
-
Save bars3s/c98ff5f535d02035b0bfe13993be9c8f to your computer and use it in GitHub Desktop.
nginx image resizer with size parameters in query string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example: test.com/images/cats.jpeg?w=100&h=100 | |
location ~* ^/images/(.+\.(?:jpe?g|png|gif))$ { | |
set $image_name $1; | |
set $demins "${arg_w}x${arg_h}"; | |
set $check_str "${demins}"; | |
# check that original size file exists | |
if ( -f $request_filename ) { | |
set $check_str "${check_str}F1"; | |
} | |
# check that width and height contain only digits and that string has file-exist flag | |
if ( $check_str ~ ^([0-9]+)x([0-9]+)F1$ ) { | |
rewrite "^/images/.+$" "/image_resize_server/${demins}/${image_name}"; | |
} | |
} | |
location ~* ^/image_resize_server/([0-9]+)x([0-9]+)/(.+)$ { | |
internal; | |
set $width $1; | |
set $height $2; | |
set $image_path $3; | |
set $demins "${width}x${height}"; | |
set $image_resized 0; | |
alias /tmp/nginx/resize/$demins/$image_path; | |
set $image_uri image_resize_process/$image_path?width=$width&height=$height; | |
if (!-f $request_filename) { | |
set $image_resized 1; | |
proxy_pass http://127.0.0.1:80/$image_uri; | |
break; | |
} | |
add_header X-debug-message "Resized: ${image_resized}"; | |
proxy_store /tmp/nginx/resize/$demins/$image_path; | |
proxy_store_access user:rw group:rw all:r; | |
proxy_temp_path /tmp/images; | |
proxy_set_header Host $host; | |
} | |
location /image_resize_process { | |
# place dir with original size images here | |
alias /var/www/site/public/images; | |
image_filter resize $arg_width $arg_height; | |
image_filter_jpeg_quality 75; | |
image_filter_buffer 10M; | |
allow 127.0.0.0/8; | |
deny all; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment