一、问题背景
使用nginx,在客户浏览器加载图片,报错信息如下,显示乱码,无法加载源图片文件:

ÿØÿà�JFIF������ÿÛ�C�#%$""!&+7/&)4)!"0A149;>>>%.DIC;ÿÛ�C;("(;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ÿÀ���"�ÿÄ��������������ÿÄ�D� ���!1AQaq‘¡±"Á2$3RÑ#Bbsð%4CSr²áñ&5TcƒÿÄ��������������ÿÄ�)������!1AQ"2aq3‘¡ÿÚ���?�ã�`)$¶ÌU+$’[lägЧk}#°ÀâÔR”½þ}ŽK“0í·ìèa¤´Œù’ÿ�ó%Ñ¿©€d6ó%Ý2]Ù¨�ÛÌ—v¼ÉwcÌ—vj�6ó%Ý2]Ù¨�ÛÌ—v¼ÉwcÌ—vj�6ó%Ý2]Ù¨�ÛÌ—v¼ÉwcÌ—vj�6ó%Ý2]Ù¨�ÛÌ—v¼ÉwcÌ—vj�6ó%Ý2]Ù¨�ÛÌ—v¼ÉwcÌ—vj�6ó%Ý2]Ù¨�ÛÌ—v
二、问题排查
Content-Type 设置不正确: 确保 Nginx 在响应中正确设置了Content-Type 头。对于图片文件,通常使用 image/jpeg、image/png 等。
三、问题解决
对应的nginx配置中,添加:
add_header content-type "image/png";
示例:
#文件上传location ^~ /service/ {proxy_pass http://x.x.x.x:58136;proxy_set_header Host "x.x.x.x6:58136";proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;add_header content-type "image/png";proxy_connect_timeout 1200;proxy_read_timeout 1200;}
或者注释掉以下配置:表示执行嗅探、自动判断文件类型。
# add_header X-Content-Type-Options nosniff;
该配置含义:强制浏览器按照服务器指定的 MIME 类型来处理资源,防止一些潜在的安全问题。告诉浏览器不要执行 MIME 类型嗅探。即使服务器返回的 Content-Type 是错误的或者不明确,浏览器也应该按照服务器声明的类型来处理内容,而不是尝试猜测内容的真实类型。
再次刷新,则加载正常:

三、自定义文件格式类型
#文件上传location ^~ /service/ {proxy_pass http://59.218.238.226:58136;proxy_set_header Host "59.218.238.226:58136";proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;if ($request_filename ~* ^.*?.(png|jpg)$) {add_header content-type "image/png";}if ($request_filename ~* ^.*?.(html|doc|zip|docx)$) {add_header Content-Disposition attachment;add_header Content-Type application/octet-stream;}if ($request_filename ~* ^.*?.(pdf)$) {add_header Content-Type 'application/pdf;';}proxy_connect_timeout 1200;proxy_read_timeout 1200;}
根据文件格式定义输出类型。

