I'm using Apache's mod_rewrite
to route requests for JPG files to a directory outside my web root.
It generally has been fine, but there are a few images that do not display. I then realized that when I use PHP's get_headers()
function on my image URLs, they are all returning
Content-Type: text/html; charset=UTF-8
Content-Type: text/html; charset=UTF-8
instead of the proper image/jpeg
header types.
I have tried explicitly setting the Content-Type: image/jpeg
header and still, none of my images return the correct headers - although most do display correctly, but I'm not sure why.
How can I assure a JPG file is sent with the correct header when redirecting via mod_rewrite
?
This is what you could do. Create a PHP file that will get the right file and passes it through
<?php
$sImage = 'imagename.jpg';
header("Content-Type: image/jpeg");
header("Content-Length: " .(string)(filesize($sImage)) );
echo file_get_contents($sImage);
or
<?php
$sImage = 'imagename.jpg';
$rFP = fopen($sImage, 'rb');
header("Content-Type: image/jpeg");
header("Content-Length: " .(string)(filesize($sImage)) );
fpassthru($rFP);
exit;
您还可以使用带有T
标志的mod_rewrite设置Content-Type标头字段:
RewriteRule … … [T=image/jpeg]
How about image which is not.jpg. Like .gif, ...
You'll need to use mime_content_type() (which is deprecated) or the fileinfo extension to determine which content-type to send.
Edit: I don't recommend this, but if you are working with a specific subset of file extensions, you could also create a small dictionary array of content-types and use the file extension to determine which one to send.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.