18
Based on this solution used in this answer in SO-en i created a . htaccess and a PHP script
.htaccess:
RewriteEngine On
RewriteCond %{HTTP:if-modified-since} .
RewriteCond %{HTTP:if-none-match} .
RewriteRule . not_modified.php [L]
not_modified.php:
<?php
if (isset($_SERVER['REDIRECT_URL'])) {
$file = $_SERVER['REDIRECT_URL'];
} else if (isset($_SERVER['REQUEST_URI'])) {
$file = $_SERVER['REQUEST_URI'];
}
$last_modified_time = filemtime($file);
$etag = md5_file($file);
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $last_modified_time) . ' GMT');
if (
strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) === $last_modified_time ||
trim($_SERVER['HTTP_IF_NONE_MATCH']) === $etag
) {
if (isset($_SERVER['SERVER_PROTOCOL'])) {
header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
} else {
header('HTTP/1.0 304 Not Modified');
}
}
The script checks for changes in the file and if there are no changes then it sends the 304 code to the client response.
My question is the following, it is possible to do this without using PHP, ie using only .htaccess
?
A question, as it was specified the 30 days, if the file is changed before that time.. it will continue to use the cache?
– Elaine
Yes @Elaine if the file saved in the person’s computer/browser cache has the same date last amendment then the server does not send the file, it only sends the 304 to reply and the browser generates a new cache with another 30 days for example.
– Guilherme Nascimento
I was a little confused. If this server-side file is changed I will get an obsolete file in the next accesses to the site or the new copy will be uploaded?
– Elaine
@Elaine will be loaded when the cache expires, so this goes from file type, you can create a
.htaccess
for each folder, if it is a folder that has content that changes very often then make a shorter cache time, if it is a folder that rarely content is changed make a larger cache.– Guilherme Nascimento