
我有一些 php 腳本,它會傳回內容類型為“image/jpeg”的 jpeg 映像(1x1 像素):
// 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 函數標頭('內容類型:圖片/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
您確定是 nginx,而不是 PHP 新增了 嗎Content-type: text/html
?從您貼上的配置來看似乎不是這樣。可能是您有其他 PHP 程式碼首先設定了它。嘗試將 PHP 標頭呼叫更改為如下所示:
header('Content-Type: image/jpeg', true);
第二個參數會覆寫該特定標頭的任何其他先前呼叫。
您可能還想查看一下$upstream_http_content_type
,它是一個 nginx 變量,其中包含Content-type
PHP 發出的標頭。如果你需要一個醜陋的 hack 來解決這個問題,你可以將它與if
你的 nginx 配置中的語句一起使用。