Erik
Erik

Reputation: 14750

How to compact nginx config for resizing images?

I have the following config for resizing images image_filter_module module with predifined sizes c64x64, c128x128, oringinal that looks like the following:

# Resize image on a fly (crop 64x64)
location ~ ^/image/c64x64/(.*):(.*)\.(?:jpg)$ {
    alias /var/www/upload/$1/$1:$2.jpg;

    image_filter crop 64 64;
    image_filter_jpeg_quality 85;
    image_filter_buffer 3M;
}

# Resize image on a fly (crop 128x128)
location ~ ^/image/c128x128/(.*):(.*)\.(?:jpg)$ {
    alias /var/www/upload/$1/$1:$2.jpg;

    image_filter crop 128 128;
    image_filter_jpeg_quality 85;
    image_filter_buffer 3M;
}

# Resize image on a fly (crop 192x192)
location ~ ^/image/c192x192/(.*):(.*)\.(?:jpg)$ {
    alias /var/www/upload/$1/$1:$2.jpg;

    image_filter crop 192 192;
    image_filter_jpeg_quality 85;
    image_filter_buffer 3M;
}

# Resize image on a fly (orig)
location ~ ^/image/original/(.*):(.*)\.(?:jpg)$ {
    alias /var/www/upload/$1/$1:$2.jpg;

    image_filter_jpeg_quality 85;
    image_filter_interlace on;
    image_filter_buffer 3M;
}

The requested images is the following http://example.org/image/c128×128/10:54ea44.jpg

This looks ugly because there is a lot of repeated peices. How could I compact mynginx config?

Upvotes: 0

Views: 2409

Answers (1)

Ivan Tsirulev
Ivan Tsirulev

Reputation: 2811

If you don't need to validate the received dimensions, then something like this will do:

# Move this line inside the location if your image root folder
# differs from your main document root
root /var/www;

location ~ ^/image/c(?<width>\d+)(×|x)(?<height>\d+)/(?<name>(?<dir>.+?):.+\.jpg)$ {
    image_filter crop $width $height;
    image_filter_jpeg_quality 85;
    image_filter_buffer 5M;

    rewrite ^.*$ /upload/$dir/$name break;
}

And if you do want to validate the parameters, then the configuration will have to get somewhat complicated:

map $request_uri $incorrect_sizes {
    default                   1;

    ~/image/c64(×|x)64/.*$    "";
    ~/image/c128(×|x)128/.*$  "";
    ~/image/c192(×|x)192/.*$  "";

    # Define here as many sets of sizes as your like
}

server {
    ...

    # Move this line inside the location if your image root folder
    # differs from your main document root
    root /var/www;

    location ~ ^/image/c(?<w>\d+)(×|x)(?<h>\d+)/(?<name>(?<dir>.+?):.+\.jpg)$ {
        image_filter crop $width $height;
        image_filter_jpeg_quality 85;
        image_filter_buffer 3M;

        if ($incorrect_sizes) {
            set $w 128;   # default width
            set $h 128;  # default height
        }

        rewrite ^.*$ /upload/$dir/$name break;
    }

    ...
}

Upvotes: 1

Related Questions