Over a million developers have joined DZone.

NGINX Plus Resizes Images for Responsive Web Design: Part I

In this blog post we show how to use the Image‑Filter module for NGINX and NGINX Plus to deliver responsive images without the headache of creating and managing a myriad of image asset variants.

· Performance Zone

Download Forrester’s “Vendor Landscape, Application Performance Management” report that examines the evolving role of APM as a key driver of customer satisfaction and business success, brought to you in partnership with BMC.

Using the Image‑Filter Module and srcset Tag to Resize Images on the Fly

Responsive web design has become the norm for modern websites and web applications, providing a consistent experience across a wide variety of devices while also optimizing the display for each device. However, modern devices vary not only in terms of screen size but also pixel density. The HTML5 img tag provides a number of features that enable the browser to select the most appropriate asset if the server provides multiple variants. By deploying different sizes of the same image, the web browser can choose the size best suited to its current environment.

Responsive images can therefore, allow the web browser to produce a rendering that closely matches the intent of the designer. This improves user experience but it also puts an additional burden on the development and operations teams, who now have to create and deploy numerous image asset variants as well as the default image.

In this blog post we show how to use the Image‑Filter module for NGINX and NGINX Plus to deliver responsive images without the headache of creating and managing a myriad of image asset variants – instead, we can deploy a single “master” version of each image that NGINX or NGINX Plus resizes on the fly. The information in the post applies to both the open source NGINX software and NGINX Plus (except for the separate instructions in Installing the Image‑Filter Module); for brevity, we refer to NGINX Plus throughout.

The srcset Attribute

The principal tool for delivering responsive images is the srcset attribute of the HTML5 img tag. We can use it to specify a number of image asset variants for different pixel densities and viewport sizes. Viewport is a generic term for the display space available to the web browser, whether it’s in a window on a desktop or a full‑screen app on a mobile device.

In the following example, the src attribute defines a default image for browsers that do not support the srcset attribute and the srcset attribute names two variants – one for displays with standard pixel density (1x), and a second for displays with double pixel density, such as Apple Retina displays and some 4K monitors (2x).

<img src="/images/mylogo-default.png"

  srcset="/images/mylogo-density1.png 1x, /images/mylogo-density2.png 2x">

This more sophisticated example defines a number of image asset variants to display, according to the width of the viewport. The sizes attribute specifies that the browser renders an image in one‑half of the viewport if the viewport is wider than 10em and uses the entire viewport otherwise. The browser determines how much space is available for the image, and selects the image asset variant that best fits the available space, typically “rounding up” to the next width (w suffix) and internally resizing the image to fill the space exactly.

<img src="/images/racecar-default.jpg"

   sizes="(min-width: 10em) 50vw, 100vw"

  srcset="/images/racecar-100px.jpg 100w, /images/racecar-225px.jpg 225w,
 /images/racecar-450px.jpg 450w, /images/racecar-675px.jpg 675w">

This approach to delivering responsive images by specifying a range of image asset variants is easy to code and highly effective. However, it presents challenges in terms of creating and managing the image variants themselves. You have to do a great deal of pre‑production image resizing and deploy a much greater number of files on the server. It can be time‑consuming to fine‑tune the optimum number and size of each variant, which then leads to difficulty in testing that each image asset variant is accessible.

For more information about the srcset attribute and other techniques for responsive images, see this great blog post.

Installing the Image‑Filter Module

The procedure for obtaining that Image‑Filter module differs for NGINX Plus and NGINX.

Installing the Image‑Filter Module for NGINX Plus

The Image‑Filter module is available as a free dynamic module for NGINX Plus subscribers.

  1. Obtain the module itself by installing it from the NGINX Plus repository.For Ubuntu and Debian systems:
    $ sudo apt-get install nginx-plus-module-image-filter
    For RedHat, CentOS, and Oracle Linux systems:
    $ sudo yum install nginx-plus-module-image-filter
  2. Enable the module by including a load_module directive for it in the top‑level (“main”) context of the nginx.conf configuration file (that is, not in the http or stream contexts).
    load_module modules/ngx_http_image_filter_module.so;
  3. Reload NGINX Plus to load the Image‑Filter module into the running instance.
    $ sudo nginx -s reload

Installing the Image‑Filter Module for Open Source NGINX

The easiest way to install the Image‑Filter module is to obtain it from the official NGINX repository. Follow these instructions to configure your system to access the official NGINX repository and then install it with your operating system package manager.

For Ubuntu and Debian systems:

$ sudo apt-get install nginx-module-image-filter

For RedHat, CentOS, and Oracle Linux systems:

$ sudo yum install nginx-module-image-filter

Once installed, follow Steps 2 and 3 in Installing the Image‑Filter Module for NGINX Plus to configure NGINX and reload.

It is also possible to compile the Image‑Filter module from source and load it as either a statically compiled or dynamic module. For details, see the NGINX Plus Admin Guide.

Matching Image Size to Pixel Density

With the Image‑Filter module, we can create and deploy a single “master” version of each image and have NGINX Plus resize it on the fly to deliver any size variants requested by the browser. We can fine‑tune responsive web pages and images entirely within the HTML source, without manually resizing and deploying images to our web server.

In this sample HTML file, we define four image variants for devices with different pixel densities.

<!DOCTYPE html>



            <title>Responsive Logo</title>


            <h2>Logo selection based on pixel density</h2>
                <img src="/img400/mylogo.png"
                    srcset="/img400/mylogo.png 1x, /img800/mylogo.png 2x, /img1200/mylogo.png 3x,
                        /img1600/mylogo.png 4x">

The /img400, /img800, /img1200, and /img1600 directories do not actually exist. Instead, the following NGINX Plus configuration matches requests for assets prefixed with /img and transforms them into requests to resize the image in the original filename (for example, mylogo.png in the preceding HTML).

server {

    listen 80;

    root /var/www/public_html;
    location ~ ^/img([0-9]+)(?:/(.*))?$ {
        alias /var/www/master_images/$2;
        image_filter_buffer 10M;
        image_filter resize $1 -;

The server block defines how NGINX Plus handles incoming HTTP requests. The listen directive tells NGINX Plus to listen on port 80 – the default for HTTP traffic. The root directive specifies the location on disk of this website. In this simple example we are using a static website hosted by NGINX Plus, but it is also common for NGINX Plus to act as a reverse proxy for dynamic content or an application connector such as FastCGI. All of these use cases can take advantage of the Image‑Filter as described here by deploying the master images to the NGINX Plus server.

The location block uses a regular expression to match requests for assets stored in any directory that starts with /img followed by one or more digits. The digits are captured as variable $1 and the filename that follows is captured as variable $2. We then use the alias directive to serve this request from the directory on disk that contains our master images. Note that this directory is not under the root path, so clients cannot request the master images directly.

As our master images are likely to be very large, perhaps thousands of pixels wide, we need to make sure that the Image‑Filter module allocates enough memory to load and resize them. In this example we use the image_filter_buffer directive to support image files of up to 10 MB in size.

Finally, the image_filter directive tells the Image‑Filter module to resize the master image to the width captured from the suffix of the /img directory name. The dash (‑) tells NGINX Plus to maintain the master image’s aspect ratio.

For the rest of the article, be on the look out for Part II, coming soon!

See Forrester’s Report, “Vendor Landscape, Application Performance Management” to identify the right vendor to help IT deliver better service at a lower cost, brought to you in partnership with BMC.


Published at DZone with permission of Liam Crilly, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}