Fixing missing Drupal 7 images

January 08, 2012

Whilst porting an old Drupal 6 site onto Drupal 7 on to a new stack: Varnish, Nginx, PHP-FPM and APC, I ran into a roadblock with the image module of Drupal 7. This is a new core module which essentially takes the function previously encapsulated in imagecache.

As implied by the name of the module, it handles images, specifically, it handles the adding of an image field to a content type in Drupal, and also allows the settings of image display presets - different versions of the images for different uses. The image module then allows you to customise the variant of the image (size, colour, shape etc.) for each display context, for example, in a list, you might use a thumbnail, the node itself a large image, the front banner a medium image etc.

The issue I ran into was not being able to get the other variant preset versions of the image on my Drupal installation. I could get the full sized, original image, but the other variants were not displayed and simply gave 404 errors back to the browser. I checked the permissions (usually the issue) but these were all consistent for allowing the PHP-FPM pool user to create within that folder.

In actuality, the issue came down to Nginx config. The image module has a series of folders it creates under 'styles/' within the public folder for Drupal uploads. For new variants of an image to be created, a 404 needs to be sent to Drupal, and then the new variant is made (rather than at the point of upload, something I didn't realise). Therefore, I needed to make sure that Nginx sent the 404s for those URLs back to Drupal for the logic to work. This is done as follows:

location @rewrite {
    rewrite ^/(.*)$ /index.php?q=$1;

location ~ ^/sites/.*/files/styles/ {
    try_files $uri @rewrite;

For those unfamiliar with Nginx config, this essentially says that for requests matching ^/sites/.*/files/styles/, Nginx should try the URI requested, and then if that fails, pass to @rewrite. @rewrite then rewites that request to Drupal, which can then handle the appropriate creation logic. With that in situ the different versions of the images are created correctly and the URLs resolve as expected.