Nginx 上の PHP スクリプトで「Content-Type」ヘッダーを上書きする方法

Nginx 上の PHP スクリプトで「Content-Type」ヘッダーを上書きする方法

コンテンツ タイプが「image/jpeg」の jpeg 画像 (1x1 ピクセル) を返す PHP スクリプトがあります。

// 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);

このスクリプトは、php5-fpm モジュールを使用して nginx/1.2.1 で実行されています。問題は、"場所 ~ \.php$「Content-Type ヘッダーがある」テキスト/html; 文字セット=UTF-8「私のPHP関数を無視してヘッダー('Content-Type: image/jpeg')結果として、「text/html」コンテンツ タイプの jpeg 画像が取得されます。

仮想ホストの簡略化された構成は次のとおりです。

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

を追加しているのは PHP ではなく nginx だと確信していますかContent-type: text/html? 貼り付けた設定からはそうは思えません。最初に設定している他の PHP コードがある可能性があります。PHP ヘッダー呼び出しを次のように変更してみてください。

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

2 番目の引数は、その特定のヘッダーに対する他の以前の呼び出しをオーバーライドします。

$upstream_http_content_typeまた、PHP が出力したヘッダーを含む nginx 変数 も確認してみるとよいでしょうContent-type。これを回避するには、ifnginx 構成内のステートメントでこれを使用できます。

関連情報