Caching HTTP Headers, Last-Modified and ETag

What if we cannot predict lifetime of page content? If we have a page with info that changes unpredictably we still can use browser cache to avoid unneeded traffic.
Using validation mechanism browser sends HTTP request with info about cache entry and server can respond that the content wasn’t changed.
There are two validation methods: one is based on Last-Modified and the other is based on Etag.

Last-Modified
Server sends Last-Modified header with datetime value that means the time when content was changed last time.
Cache-Control: must-revalidate
Last-Modified: 15 Sep 2008 17:43:00 GMT

The first header Cache-Control: must-revalidate means that browser must send validation request every time even if there is already cache entry exists for this object.
Browser receives the content and stores it in the cache along with the last modified value.
Next time browser will send additional header:
If-Modified-Since: 15 Sep 2008 17:43:00 GMT

This header means that browser has cache entry that was last changed 17:43.
Then server will compare the time with last modified time of actual content and if it was changed server will send the whole updated object along with new Last-Modified value.

If there were no changes since the previous request then there will be short empty-body answer:
HTTP/1.x 304 Not Modified

And browser will use the cached content.

What if server doesn’t send Cache-Control: must-revalidate?
Then modern browsers look at profile setting or decide on their own whether to send conditional request. So we better to send Cache-Control to make sure that browser sends conditional request.

Sample PHP code:

$last_modified_ts = floor(mktime()/30)*30;
if (
isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $last_modified_ts
)
{
header('HTTP/1.1 304 Not Modified');
exit;
}
header('Cache-Control: must-revalidate');
header('Last-Modified: '.gmdate('d M Y H:i:s',$last_modified_ts).' GMT');
echo date('d M Y H:i:s');

This example outputs cached datetime that’s expiring every 30 seconds.

Last-Modified suits good in case we can easily calculate modification time of page content.

We must be careful with Last-Modified if we have page content that consists many fragments. We should calculate Last-Modified value of every fragment and get the latest one.
Note that if we have authentication and there is a page fragment that depends on authentication we have to reset Last-Modified value after login/logout – for every page that contains the fragment.
Also note that in case of several web servers we should make sure that Last-Modified value changes synchronous for all the servers.

ETag
This method suits for cases when it’s difficult to maintain Last-Modified value: when you have complicated application with many page fragments especially if there are third-party libraries. Or for the case with authentication, when page content depends on authentication info.
There is simple idea besides ETag:
ETag value depends on the content and must be different for different content and the same for the same content.

Sample usage of ETag header:
$content = floor(mktime()/30)*30;
$etag = md5($content);
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $etag)
{
header('HTTP/1.1 304 Not Modified');
exit;
}
header('Cache-Control: must-revalidate');
header('ETag: '.$etag);
echo $content;
echo '
Request time: '.date('d M Y H:i:s');

In this example content changes every 30 seconds and browsers will download only if the content was changed.

Static Content and Unnecessary ETag Header
For static content it’s recommended to send Cache-Control: max-age=… header with higher max-age value. In this case browser won’t send any request on normal page views.
So for static content there is no use of ETag header.
The worse case is in case of web servers cluster as ETag value differs for the file on different servers.
For Lighttpd server you can disable Etag using
static-file.etags = 'disable'
in lighttpd.conf

Disabling ETag in Apache:
Header unset ETag
FileETag None

Note that we still want Last-Modified header for static files. If user presses Refresh button, then browser will send conditional request and server will respond “304 Not Modified”.
And if you disable both Last-Modified and ETag browser will have to download the whole content again when user presses Refresh.

Lighttpd and Apache will send Last-Modified if you have configured mod_expires.

44 thoughts on “Caching HTTP Headers, Last-Modified and ETag

  1. i have last-modified and max-age directive for static files, yet with firefox, it still will request files even if they are cached.

    best.

  2. Pingback: Configure or Remove ETags in Apache/HTTP

  3. Seo-Progon.Info – сервис быстрого постинга в форумы, блоги, гостевые, соц. закладки, каталоги статей, каталоги сайтов. Проект сочетает в себе ряд оригинальных особенностей: простота и функциональность, доступная цена, отличная эффективность регистрации и часто обновляемые базы.
    Что мы даем:
    - Постинг в русскоязычных форумах.
    - Постинг в англоязычных форумах.
    - Постинг по профилям русскоязычных и англоязычных форумов.
    - Постинг по блогах.
    - Постинг на гостевым книгам.
    - Постинг по WIKI.
    - Регистрация в каталагах сайтов.
    - Регистрация на каталогах статей.
    Основные функции системы:
    1. Автоматическая система прогона.
    2. Удобный и простой генератор описаний.
    3. Постоянно обновляемые базы.
    Дополнительные возможности системы:
    1. Естественное сабмит в поисковики.
    2. Автоматизированный прием платежей.
    3. Отчеты о выполненном постинге.
    4. Выгодная партнерская программа для вебмастеров.

    Seo-Progon.Info

  4. Prior to starting to talk about UGG boots, I have to very first handle those folks around the globe, who have no idea in any respect as to ugs co uk what UGG boots in fact are. These are boot styles are of Australian make and use sheepskin as their raw materials. They have fleece around the inner facet and also a tanned outer layer. Aside from shoes or boots for uggboots adults, in addition they manufacture kid’s footwear.

    The background with the usage of those boots is pretty fascinating. Pilots utilised to put on these ugg australlia fleece lined boots during the First Globe War and it has also been discovered that farmers in Australia, within the 1930s applied to put on UGG boots too for maintaining their ft warm and cozy. It utilised to serve the same objective for the surfers as they too needed some warmth for their feet to resume some blood circulation after truly lengthy hrs at the sea. The range of UGG kid’s boots are manufactured with specifically the habits with the kids in thoughts. They are a restless bunch of young children and so that they locate it genuinely uncomplicated to slip in and out of those ” booties “.

    UGG kid’s footwear have proved to stand tall to the check time. If these boot styles were a rage last season, they are able to still show being the trendsetter’s preferred more than the many years. A host of celebrities from Oprah Winfrey to Paris Hilton have sworn by these boots. UGG boot styles can appropriately be termed as the focal point the place comfort and fashion meet. Though UGG boots basically meant ugly boot styles, when they’re worn, they appear something but ugly.

    The UGG kid’s boot styles look to pay plenty of focus to the truth that kids nowadays are very fashion aware and love to dress properly and seem good. That’s possibly the cause why cheap real uggs the business manufactures boot styles for them that are in shiny shades and look funky. To cater to diverse tastes there are two kinds of lengths readily available, the lengthy as well as the brief. These boot styles are thus a ought to have inside the cupboard s of youngsters spread all through the planet.

    The Children Uggs ugg boots online also come in quite small sizes which are appropriate for infants whose age varies from newborns to about two 12 months olds. These ” booties ” are fitted with Velcro in order that no dilemma arises involving the slipping on and off of those footwear.
    For the parents who are now keen to find out their children’s faces glow with pleasure, your best alternative would be to go to kidsshoesdirect.co.uk. These guys save a enormous collection of Children Ugg Shoes or boots and at amazingly beneficial bargains. The key for your child’s happiness ugg boots from australia
    is only a click on away.

  5. Hi,

    I’m using HTTP Watch. Now, when i open a particular page. I see few components (say 42 occurences) as 304 not-modified and few components as Cached. I simply cannot understand the difference b/w the two as both are coming from caches. Everytime i load the page the occurences for 304-not modified keeps changing (say 15 occurences the 2nd time). I’m really getting confused.
    My question is
    1) on what all settings will i get 304 not modified. (FYI : currently what i see is Cache-control = private ;; also ETAG is set)
    2) on what all settings the page will be retreived just from cache without any validation i.e i dont want 304 not modified but still from cache (FYI :the components which are Cached in my capture, have ETAG set)
    3) Why the no. of occurences keep changing on next page load???

  6. Pingback: Seiten laden beim Navigieren immer neu - XHTMLforum

  7. http://classsex.ru/sex/465.jpg
    http://opapizda.com/img/9/index.jpg
    http://tdq.in/images/1/396.jpg

    стерлитамак порно фото
    конторсия секс
    пизду секс фото
    маленькие члены порно
    кино эротика
    порно 15
    ремень порно
    эротика юмор
    порно фото лель
    анджелина порно

    Карта сайта
    Porno X World Com
    Экстримальный Секс Фото
    Порно Фото Студенты
    Карта сайта
    Porn Letitbit
    Карта сайта
    Sex Костюмы
    Порно Мичуринска
    Клизма Порно Клипы
    Демо Порно Видео Ролики
    Хочу Секс Липецк – зрелых парнуха фильм
    Cекс Знакомства Екатеринбурга
    Фото Дикого Секса
    Карта сайта
    Карта сайта
    Секс Садомазохизм
    Видео Ролики Секс Эротика
    Wicked Sex Party 3
    Порно Фото Звезд
    Www Русское Porno
    Карта сайта
    Мамаш Ебёт Сына
    Real Порно
    Порно Лунка 1
    Посмотреть Сейчас Порно
    Сиськи Галлерея
    Секс Spears
    Секс Серебряный Бор
    Отношения Без Секса Психология
    Карта сайта
    Карта сайта
    Секс Фото Нудистские
    Иваново Знакомства Секс
    Секс Первая Кровь
    Инцест Порно Старые
    3gp Видео Без Порно
    Секс Девчками Фото Видео
    Голые Женские Письки
    Плохой Секс – голые девочка видео
    Кино Секс Миссия Польский
    Pamela Порно
    Мужчина Рак Секс
    Карта сайта

    порно мир
    porno star sexnarod
    эротика вэб камера
    ампутирована рука секс
    бузова секс
    ананас секс
    просмотр порно овидий без скачивания
    ищем групповой секс
    секс 1 2 раза
    доска объявлений порно
    межрассовый секс
    секс любовь
    порно находки
    медсёстры секс
    порно бузовой
    секс бар
    порно грудь фото
    порно картинки галереи
    фото волосатые женские пизды
    пизда бритни спирс
    рисованный секс
    порно jessica alba
    3 gp порно видео

  8. проститутка Мелания где в кирове заказать проститутку где найти недорогую проститутку
    проститутки янгеля анкеты проституток краснодара топ проституток
    проститутка людмила метро новокузнецкая проститутки питера индевидуалки проститутки приозерска
    проститутки трансы порно самая дорогоя проститутка м парк культуры проститутка

    праститутки винкс проститутки санк петербурга проститутки люблино апартаменты
    элитные проститутки г киева проститутки приморский край город артем праститутки москвы метро
    проститутки москвы госпожа сколько стоит проститутка на ночь проститутки москвы фото
    красноярск дешёвые проститутки в возрасте проститутки Терек московские праститутки фото

  9. http://classsex.ru/sex/297.jpg
    http://opapizda.com/img/11/index.jpg
    http://tdq.in/images/1/149.jpg

    порно фото волосатых
    порно гомосексуалистов
    какие хуи
    порнуха без регестрацыи
    www porno fr
    e2 eros
    porn narod
    порно качки
    секс века
    женщина секс власть благодать

    Знакомства секс симферополь
    Самая качественная секс игра 3d
    Porn
    Афоризмы про секс
    Случайный секс
    Секс порно спожылыми женщинами
    Секс еротика
    Видео секс порно посмотреть
    Порно sex video
    Телки знакомства
    домашнее порнуха фильм
    Порно секс ню
    House porno
    Секс музеи
    Видео фильмы tv порно онлайн
    Sex willa
    Sims секс
    Порно подрочить
    Секс инопланетянка
    Teen порно фото
    Криодеструкция эрозии анальный секс
    Sex books ru
    Sex woman
    Секс любовь обнинск симпатичный парень
    Вип порно
    Секс знакомства электросталь
    Просмотр порно видео интернете
    Силиконовые сиськи ru
    Анальный секс опасность
    Фото девушек красивых секс
    Менструальный цикл секс

    эротические фильмы ролики
    порно обои девушки
    волочек секс
    секс штучки
    волосатый секс
    секреты анального секса
    демо порно видео ролики
    студенты порно фото
    cекс со взрослыми женщинами
    порно огурец
    пизда шарон стоун
    порно галерея маленьких
    крутая порнография
    посмотреть порно ххх
    порно сайт маргарита
    фото порно личное
    хачу секс
    русская порно
    фото эротика любители
    порно расскказы
    секс туризм вьетнам
    попы сиски
    фото больших телок

  10. Google analysis reveals that http://www.jamaicastores.com needs the etag and last modified tag to help my page load faster. DO I just use the info you have posted here and put it into the header of my page? How do I change the time to be in days?

    Thanks

  11. Watching TV without disconcerting others is a big fine kettle of fish as a replacement for me. I like to attend TV in bed and my wife always complains with regard to the noise and we result up having arguments onto it. This is why I started looking in return some headphones to inject while watching TV. I came across these wireless headphones that are least affordable and any more I don’t tend TV with anything other than a yoke of Sennheiser RS 130 Wireless Environment Give one the impression Headphones. If you are bigwig who exceptionally likes having an staggering acoustic encounter while watching TV, then you really necessity to check not on this product.

    We on discover people talk upon the fact that substantially all headphones are the same. They make the position that it doesn’t really shape any sensation to become short of your in the pipeline to achieve a outrageous eminence matched set of headphones because you intention not really get any better grade outside of them. Nothing could be in addition from the truth. I am somebody who has experimented with a wide variety of headphones. Forget in the air the pygmy earbuds that typically penetrate packaged with your TV – they exceedingly don’t work. Grandly, they enlarge on a excite, but second you sample on a dyad of Sennheiser RS 130 Wireless Surround Resound Headphones you last wishes as on no account after to take a leak back to using anything else.

    The Rs 130 draw transmits crystal set frequencies on three contrastive channels so as to sidestep interference. This can go through with the aid walls and has a fairly unconfined wireless range.

    The headphones don’t need to be plugged in to be charged all you have occasion for to do is tarry it up on the infrastructure position for it to charge. The headphones are powered aside thriple A batteries. The batteries last roughly 22 hours after you responsibility them. Interest note these headphones are open backed so if you arrange someone sitting aright next to you they will be masterful to hear some of the sound. But this generous backed connivance helps a destiny with hearing quality as the diaphragm has less obstruction and can impel requital and forth noticeably freely. Audio is friable and explicit and for the duration of the simple easily fetch of these headphones is more than reasonable.

    The padded notice pieces are certainly contented and fits all over the ear comfortably.

    These headphones entertain an auto power switch which switches the organization slow when no sound produce is received because 1 minute. This takes prevalent 3 seconds to reconnect and you last wishes as miss the audio in that time. So if you are listening to something signal it on be unreservedly annoying to miss it. But this physiognomy helps save battery power.

    When watching movies and in return playing games you can turn on the surround sound peculiarity and the atmosphere sound effects are nice-looking impressive. Fifty-fifty supposing this is not unvarnished environs touched off, in the service of such a inexpensive pinpoint of headphones, it is really exceptional. The however true error I could encounter with these is that the open backed main attraction of the supervisor sets doesn’t brook in place of quiet listening. Anyone sitting join to you will be adept to agree what you are listening to. But this is quiet plenty for the sake of my helpmeet to drowse help of it.

    I highly persuade buying a pair of these headphones online. It commitment set free you from having to go to a store. If you come off to be a rococo professional, then you know how obscure it can at times be to remark the patch to go to the stores anyway. You non-standard real won’t be your determination, and I contemplate at the end of the daytime, you pass on all things considered supersede up potent all of your friends that they have occasion for to open to minus and pay off a matched set of Sennheiser RS 130 Wireless Setting Strike one Headphones too!

    review sennheiser rs 170

  12. Thank you for another informative site. Where else may just I am getting that type of information written in such a perfect approach? I have a mission that I’m just now running on, and I’ve been on the look out for such info.

  13. It is truly a nice and helpful piece of info. I am satisfied that you shared this useful information with us. Please stay us informed like this. Thanks for sharing.

  14. I relish, lead to I found just what I used to be taking a look for. You’ve ended my four day lengthy hunt! God Bless you man. Have a nice day. Bye

  15. I am now not positive the place you are getting your info, but good topic. I must spend some time studying much more or understanding more. Thank you for fantastic info I was on the lookout for this information for my mission.

  16. Wonderful work! This is the kind of info that should be shared around the internet. Shame on Google for no longer positioning this submit higher! Come on over and talk over with my web site . Thanks =)

  17. Thank you for the good writeup. It in truth was a amusement account it. Glance complicated to more introduced agreeable from you! By the way, how can we communicate?

  18. I was recommended this website via my cousin. I am now not certain whether or not this submit is written via him as nobody else realize such precise approximately my trouble. You’re amazing! Thanks!

  19. for a long time simply because about my heart, with your core! Our favorite widespread wish to have an enjoyable intend Chaoyang marvellous positive lifestyle! ! !

  20. for those who choose buyers relaxation and therefore happiness just about forever, gladly to booty day by day! Goal focussed reliable accord! With out could be thinking Addition at the experience. Thinking

  21. It is actually a great and helpful piece of info. I am happy that you shared this helpful info with us. Please stay us informed like this. Thanks for sharing.

  22. I am really inspired along with your writing skills and
    also with the format in your weblog. Is this a paid theme or did you customize it yourself?
    Either way stay up the nice high quality writing, it is rare to look a nice blog like this one nowadays.
    .

  23. Most computers employed in business, and many found in the
    home, no more operate inside old self contained fashion.
    They are higher quality to recognize hard to understand accents and alterations in the
    way people speech. The biggest flaws with grease traps and grease interceptors are sizing, pumping, and odors.

  24. We know it is human nature to devalue the things we receive for free.

    In case fire or explosion does occur, immediately smother
    the fire with a thick blanket or non-flammable material to remove oxygen since fire cannot be sustained
    in the absence of this element. These craftsmen have the knowledge, tools and time
    to ensure your home.

  25. First, Pinterest users should have more creative options to customize the home page.

    Unfortunately, it’s also introduced a host of ways to violate intellectual property laws.

    The more powerful the image, the more interest you will provoke
    in visitors to your profile which in turn will result in your profile attracting more followers.

  26. Wow! This can be one particular of the most helpful blogs We have ever arrive across on this subject. Actually Excellent. I’m also an expert in this topic therefore I can understand your effort.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>