4

I have some php script which returns jpeg image(1x1 pixel) with content type "image/jpeg":

// return image
$image_name = 'img/pixel.jpg';
$image = fopen($image_name, 'rb');
header('Content-Length: ' . filesize($image_name));
header('Content-Type: image/jpeg');
fpassthru($image);

This script running on nginx/1.2.1 with php5-fpm module. Problem is that all responses from requests that match "location ~ \.php$" have Content-Type header "text/html; charset=UTF-8", ignoring my php function header('Content-Type: image/jpeg'). As a result i get jpeg picture with "text/html" content type.

Here's a simplified configuration of my virtual host:

server {
    listen                  80;
    server_name             localhost default_server;

    set                     $main_host      "localhost";
    root                    /var/www/$main_host/www;

    location / {
        root  /var/www/$main_host/www/frontend/web;
        try_files  $uri /frontend/web/index.php?$args;

        location ~* ^/(.+\.(css|js|jpg|jpeg|png|gif|bmp|ico|mov|swf|pdf|zip|rar))$ {
            try_files  $uri /frontend/web/$1?$args;
        }
    }

    location /admin {
        alias  /var/www/$main_host/www/backend/web;
        try_files  $uri /backend/web/index.php?$args;

        location ~* ^/admin/(.+\.php)$ {
            try_files  $uri /backend/web/$1?$args;
        }

        location ~* ^/admin/(.+\.(css|js|jpg|jpeg|png|gif|bmp|ico|mov|swf|pdf|zip|rar))$ {
            try_files  $uri /backend/web/$1?$args;
        }
    }

    location ~ \.php$ {
        try_files  $uri /frontend/web$uri =404;

        include             fastcgi_params;

        fastcgi_pass        unix:/var/run/php5-fpm.www.sock;
        fastcgi_param       SCRIPT_FILENAME     $document_root$fastcgi_script_name;
    }
}

1 Answers1

1

Are you sure that it's nginx, and not PHP which is adding the Content-type: text/html? It doesn't seem that way from your pasted config. It could be that you have other PHP code which is setting it firsst. Try changing your PHP header call to look like this:

header('Content-Type: image/jpeg', true);

The second argument overrides any other prior calls for that specific header.

You may also want to do some looking at $upstream_http_content_type, which is an nginx variable that contains the Content-type header that PHP emitted. If you need an ugly hack around this, you can use it with an if statement in your nginx config.

Andy Fowler
  • 421
  • 5
  • 5