开发者

How to prevent browsers from caching an image? [duplicate]

开发者 https://www.devze.com 2023-03-06 16:39 出处:网络
This question already has answers here: How to force a web browser NOT to cache images (20 answers) 开发者_如何学编程
This question already has answers here: How to force a web browser NOT to cache images (20 answers) 开发者_如何学编程 Closed 3 years ago.

I have one image on my website that I don't want cached. The image is used as a background in CSS so I can not change it's name dynamically. Any ideas ?


Another alternative would be to add a random string after your image file.

<img src="/path/to/image/image.jpg?<?php echo time(); ?>/>

This should ensure that the image is reloaded each time the page is displayed.


mnot has a good caching tutorial that will explain how to set the HTTP headers to request that the image is not cached (remember, you need to set the HTTP headers for the image, not the HTML document).

This is probably a bad idea though as images tend to be relatively chunky, so redownloading it for every page could impose a significant performance slow down.


with apache you cant achieve this in 2 different ways:

with mod_headers:

<FilesMatch "\.(png|jpg|jpeg|jpeg)$">
Header set Expires "Fri, 04 Aug 1978 12:00:00 GMT"
Header set Cache-Control "no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, no-transform"
Header set Pragma "no-cache"
</FilesMatch>

or with mod_expires:

<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType image/png A0
  ExpiresByType image/gif A0
  ExpiresByType image/jpg A0
  ExpiresByType image/jpeg A0
</IfModule>


If you can't set up caching rules on Apache (as suggested by @David Dorvard's answer - see the part using the <Files directive), you could pipe the image through a PHP script, and set your own (no)caching headers there:

<?php 
header('Cache-Control: no-cache');
header('Expires: 0');
header('Content-Type: image/jpeg'); // or whatever your image is
readfile('/some/path/to/yourfile.jpg');
?>

This should get you an image that's not cached at all; emphasis on should, as various browsers are variously broken (IIRC IE6 cached it anyway when linked as background-image, but thankfully that's on the way out).

Note that this simplistic approach will 1) increase the load on the server as it needs to start PHP for the image request and 2) disable partial download on the script/image


If you are targeting modern browsers you could use an HTML5 Manifest file: http://diveintohtml5.ep.io/offline.html#network

0

精彩评论

暂无评论...
验证码 换一张
取 消