Mastering Nginx

(Ron) #1
Chapter 7

[ 183 ]

Using these directives, we can construct an image resizing module as follows:


location /img {

try_files $uri /resize/$uri;

}

location ~* /resize/(?.<name>.*)_(?<width>[[:digit:]]*)
x(?<height>[[:digit:]]*)\.(?<extension>gif|jpe?g|png)$ {

error_page 404 = /resizer/$name.$extension?width=$width&height=$
height;

}

location /resizer {

image_filter resize $arg_width $arg_height;

}

This little snippet will first try to serve an image as requested in the URI. If it


cannot find an appropriately-named image, it will then move on to the /resize
location. The /resize location is defined as a regular expression so that we can


capture the size we'd like the image to be. Note that we use named capture groups
to create meaningful variable names. We then pass these on to the /resizer


location so that we have the name of the original file as the URI and the width


and height as named arguments.


We can now combine this with NGINX's proxy_store or proxy_cache capability to


save the resized images so that another request for the same URI won't need to hit
the image_filter module:


server {

root /home/www;

location /img {

try_files $uri /resize/$uri;

}

location /resize {

error_page 404 = @resizer;
Free download pdf