How to force cache cleaning in my visitors' browsers

4

I usually update my site style sheet (CSS) a lot. What happens is that my visitors see no differences. Is there any script or something that forces cleaning? Example: On next access the cache will be cleared. Some cookie that makes the cache last only 3 days for example. I just do not know what to do.

    
asked by anonymous 18.06.2014 / 06:00

2 answers

6

For Apache, you can make use of the htaccess file with the cache control directives that tell browsers how long they should download a new version of each file.

Some examples:

Header unset Pragma
FileETag None
Header unset ETag

# 1 Ano (limitado a ficheiro media)
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|mp3|mp4)$">
Header set Cache-Control "public"
Header set Expires "Thu, 15 Apr 2010 20:00:00 GMT"
Header unset Last-Modified
</FilesMatch>

# 2 Horas (limitado a ficheiro conteúdos)
<FilesMatch "\.(html|htm|xml|txt|xsl)$">
Header set Cache-Control "max-age=7200, must-revalidate"
</FilesMatch>

# Em cache para sempre (scripts e folhas de estilo)
<FilesMatch "\.(js|css)$">
Header set Cache-Control "public"
Header set Expires "Thu, 15 Apr 2010 20:00:00 GMT"
Header unset Last-Modified
</FilesMatch>

Example of caching in CSS files limited to 3 days

  • Create .htaccess file in the root of the folder containing the target files;
  • Write the appropriate cache control into the file;
  • Indicate the file extensions assigned to the control to be applied:

    # extensões separadas por um |
    <FilesMatch "\.(css)$"> 
    
  • Specify the duration of the cache so that the server tells the browser that a certain file is only valid for the time indicated, after which another one must be collected:

    # max-age = XX segundos
    Header set Cache-Control "max-age=259200, must-revalidate" 
    
  • The result of the file to use is:

    Header unset Pragma
    FileETag None
    Header unset ETag
    
    # 3 Dias
    <FilesMatch "\.(css)$">
    Header set Cache-Control "max-age=259200, must-revalidate"
    </FilesMatch>
    
        
    18.06.2014 / 11:42
    3

    You can in PHP modify the page cache:

    <?php
    //Prevent page caching
     header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
     header("Cache-Control: no-cache");
     header("Pragma: no-cache");
    ?>
    

    Or you can use a TIME in the css link, example:

    <link rel="stylesheet" type="text/css" media="screen" href="estilo.css?<?php echo time(); ?>" /> 
    
        
    18.06.2014 / 06:09