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 기능을 무시하고header('콘텐츠 유형: 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);

두 번째 인수는 해당 특정 헤더에 대한 다른 이전 호출을 재정의합니다.

$upstream_http_content_typePHP가 내보낸 헤더를 포함하는 nginx 변수인 를 살펴보는 것도 좋습니다 Content-type. 이에 대한 추악한 해킹이 필요한 경우 ifnginx 구성의 명령문 과 함께 사용할 수 있습니다 .

관련 정보