Académique Documents
Professionnel Documents
Culture Documents
http://www.mnot.net/cache_docs/#WORK
forWebAuthorsandWebmasters
1. WhatsaWebCache?Whydopeopleusethem? 2. KindsofWebCaches 1. BrowserCaches 2. ProxyCaches 3. ArentWebCachesbadforme?WhyshouldIhelpthem? 4. HowWebCachesWork 5. How(andhownot)toControlCaches 1. HTMLMetaTagsvs.HTTPHeaders 2. PragmaHTTPHeaders(andwhytheydontwork) 3. ControllingFreshnesswiththeExpiresHTTPHeader 4. CacheControlHTTPHeaders 5. ValidatorsandValidation 6. TipsforBuildingaCacheAwareSite 7. WritingCacheAwareScripts 8. FrequentlyAskedQuestions 9. ImplementationNotesWebServers 10. ImplementationNotesServerSideScripting 11. ReferencesandFurtherInformation 12. AboutThisDocument
AWebcachesitsbetweenoneormoreWebservers(alsoknownasoriginservers)and aclientormanyclients,andwatchesrequestscomeby,savingcopiesoftheresponses likeHTMLpages,imagesandles(collectivelyknownasrepresentations)for itself.Then,ifthereisanotherrequestforthesameURL,itcanusetheresponsethat ithas,insteadofaskingtheoriginserverforitagain. TherearetwomainreasonsthatWebcachesareused: ToreducelatencyBecausetherequestissatisedfromthecache(whichis closertotheclient)insteadoftheoriginserver,ittakeslesstimeforittogetthe representationanddisplayit.ThismakestheWebseemmoreresponsive. ToreducenetworktracBecauserepresentationsarereused,itreducesthe amountofbandwidthusedbyaclient.Thissavesmoneyiftheclientispayingfor trac,andkeepstheirbandwidthrequirementslowerandmoremanageable.
1 of 14
12/4/2012 1:24 AM
http://www.mnot.net/cache_docs/#WORK
BROWSER CACHES
IfyouexaminethepreferencesdialogofanymodernWebbrowser(likeInternet Explorer,SafariorMozilla),youllprobablynoticeacachesetting.Thisletsyouset asideasectionofyourcomputersharddisktostorerepresentationsthatyouveseen, justforyou.Thebrowsercacheworksaccordingtofairlysimplerules.Itwillcheckto makesurethattherepresentationsarefresh,usuallyonceasession(thatis,theonce inthecurrentinvocationofthebrowser). Thiscacheisespeciallyusefulwhenusershitthebackbuttonorclickalinktoseea pagetheyvejustlookedat.Also,ifyouusethesamenavigationimagesthroughout yoursite,theyllbeservedfrombrowserscachesalmostinstantaneously.
PROXY CACHES
Webproxycachesworkonthesameprinciple,butamuchlargerscale.Proxiesserve hundredsorthousandsofusersinthesameway;largecorporationsandISPsoften setthemupontheirrewalls,orasstandalonedevices(alsoknownasintermediaries). Becauseproxycachesarentpartoftheclientortheoriginserver,butinsteadareout onthenetwork,requestshavetoberoutedtothemsomehow.Onewaytodothisisto useyourbrowsersproxysettingtomanuallytellitwhatproxytouse;anotherisusing interception.InterceptionproxieshaveWebrequestsredirectedtothembythe underlyingnetworkitself,sothatclientsdontneedtobeconguredforthem,oreven knowaboutthem. Proxycachesareatypeofsharedcache;ratherthanjusthavingonepersonusing them,theyusuallyhavealargenumberofusers,andbecauseofthistheyarevery goodatreducinglatencyandnetworktrac.Thatsbecausepopularrepresentations arereusedanumberoftimes.
GATEWAY CACHES
Alsoknownasreverseproxycachesorsurrogatecaches,gatewaycachesarealso intermediaries,butinsteadofbeingdeployedbynetworkadministratorstosave bandwidth,theyretypicallydeployedbyWebmastersthemselves,tomaketheirsites morescalable,reliableandbetterperforming. Requestscanberoutedtogatewaycachesbyanumberofmethods,buttypically someformofloadbalancerisusedtomakeoneormoreofthemlookliketheorigin servertoclients. Contentdeliverynetworks(CDNs)distributegatewaycachesthroughouttheInternet (orapartofit)andsellcachingtointerestedWebsites.SpeederaandAkamaiare examplesofCDNs. Thistutorialfocusesmostlyonbrowserandproxycaches,althoughsomeofthe informationissuitableforthoseinterestedingatewaycachesaswell.
WebcachingisoneofthemostmisunderstoodtechnologiesontheInternet. Webmastersinparticularfearlosingcontroloftheirsite,becauseaproxycachecan hidetheirusersfromthem,makingitdiculttoseewhosusingthesite. Unfortunatelyforthem,evenifWebcachesdidntexist,therearetoomanyvariables ontheInternettoassurethattheyllbeabletogetanaccuratepictureofhowusers seetheirsite.Ifthisisabigconcernforyou,thistutorialwillteachyouhowtogetthe statisticsyouneedwithoutmakingyoursitecacheunfriendly. Anotherconcernisthatcachescanservecontentthatisoutofdate,orstale. However,thistutorialcanshowyouhowtocongureyourservertocontrolhowyour contentiscached. Ontheotherhand,ifyouplanyoursitewell,cachescanhelpyourWebsiteload
2 of 14
12/4/2012 1:24 AM
http://www.mnot.net/cache_docs/#WORK
faster,andsaveloadonyourserverandInternet link.Thedierencecanbedramatic;asitethatis diculttocachemaytakeseveralsecondstoload, whileonethattakesadvantageofcachingcan seeminstantaneousincomparison.Userswill appreciateafastloadingsite,andwillvisitmore often. Thinkofitthisway;manylargeInternet companiesarespendingmillionsofdollarssetting upfarmsofserversaroundtheworldtoreplicate theircontent,inordertomakeitasfasttoaccess aspossiblefortheirusers.Cachesdothesamefor you,andtheyreevenclosertotheenduser.Best ofall,youdonthavetopayforthem. Thefactisthatproxyandbrowsercacheswillbe usedwhetheryoulikeitornot.Ifyoudont congureyoursitetobecachedcorrectly,itwillbe cachedusingwhateverdefaultsthecaches administratordecidesupon.
CDNsarean interesting development,because unlikemanyproxy caches,theirgateway cachesarealigned withtheinterestsof theWebsitebeing cached,sothatthese problemsarentseen. However,evenwhen youuseaCDN,you stillhavetoconsider thattherewillbe proxyandbrowser cachesdownstream.
Allcacheshaveasetofrulesthattheyusetodeterminewhentoservea representationfromthecache,ifitsavailable.Someoftheserulesaresetinthe protocols(HTTP1.0and1.1),andsomearesetbytheadministratorofthecache (eithertheuserofthebrowsercache,ortheproxyadministrator). Generallyspeaking,thesearethemostcommonrulesthatarefollowed(dontworryif youdontunderstandthedetails,itwillbeexplainedbelow): 1. Iftheresponsesheaderstellthecachenottokeepit,itwont. 2. Iftherequestisauthenticatedorsecure(i.e.,HTTPS),itwontbecached. 3. Acachedrepresentationisconsideredfresh(thatis,abletobesenttoaclient withoutcheckingwiththeoriginserver)if: Ithasanexpirytimeorotheragecontrollingheaderset,andisstillwithin thefreshperiod,or Ifthecachehasseentherepresentationrecently,anditwasmodied relativelylongago. Freshrepresentationsareserveddirectlyfromthecache,withoutcheckingwith theoriginserver. 4. Ifarepresentationisstale,theoriginserverwillbeaskedtovalidateit,ortellthe cachewhetherthecopythatithasisstillgood. 5. Undercertaincircumstancesforexample,whenitsdisconnectedfroma networkacachecanservestaleresponseswithoutcheckingwiththeorigin server. Ifnovalidator(anETagorLast-Modifiedheader)ispresentonaresponse,andit doesnthaveanyexplicitfreshnessinformation,itwillusuallybutnotalwaysbe considereduncacheable. Together,freshnessandvalidationarethemostimportantwaysthatacacheworks withcontent.Afreshrepresentationwillbeavailableinstantlyfromthecache,whilea validatedrepresentationwillavoidsendingtheentirerepresentationoveragainifit hasntchanged.
3 of 14
12/4/2012 1:24 AM
http://www.mnot.net/cache_docs/#WORK
toolswithyourserver,seetheImplementation sectionsbelow.
Ifyoursiteishosted atanISPorhosting farmandtheydont giveyoutheabilityto setarbitraryHTTP headers(like Expiresand Cache-Control), complainloudly; thesearetools
necessaryfordoing HTTP/1.1 200 OK Date: Fri, 30 Oct 1998 13:19:41 GMT yourjob. Server: Apache/1.3.3 (Unix) Cache-Control: max-age=3600, must-revalidate Expires: Fri, 30 Oct 1998 14:19:41 GMT Last-Modified: Mon, 29 Jun 1998 02:28:12 GMT ETag: "3e86-410-3596fbbc" Content-Length: 1040 Content-Type: text/html
TheHTMLwouldfollowtheseheaders,separatedbyablankline.Seethe ImplementationsectionsforinformationabouthowtosetHTTPheaders.
4 of 14
12/4/2012 1:24 AM
http://www.mnot.net/cache_docs/#WORK
AlthoughtheExpiresheaderisuseful,ithas somelimitations.First,becausetheresadate involved,theclocksontheWebserverandthe cachemustbesynchronised;iftheyhavea dierentideaofthetime,theintendedresults wontbeachieved,andcachesmightwrongly considerstalecontentasfresh. AnotherproblemwithExpiresisthatitseasyto forgetthatyouvesetsomecontenttoexpireata particulartime.IfyoudontupdateanExpires timebeforeitpasses,eachandeveryrequestwill gobacktoyourWebserver,increasingloadand latency.
Itsimportanttomake surethatyourWeb serversclockis accurateifyouusethe Expiresheader. Onewaytodothisis usingtheNetwork TimeProtocol(NTP); talktoyourlocal systemadministrator tondoutmore.
HTTP1.1introducedanewclassofheaders,Cache-Controlresponseheaders,to giveWebpublishersmorecontrolovertheircontent,andtoaddressthelimitationsof Expires. UsefulCache-Controlresponseheadersinclude: max-age=[seconds]speciesthemaximumamountoftimethata representationwillbeconsideredfresh.SimilartoExpires,thisdirectiveis relativetothetimeoftherequest,ratherthanabsolute.[seconds]isthenumberof secondsfromthetimeoftherequestyouwishtherepresentationtobefreshfor. s-maxage=[seconds]similartomax-age,exceptthatitonlyappliestoshared (e.g.,proxy)caches. publicmarksauthenticatedresponsesascacheable;normally,ifHTTP authenticationisrequired,responsesareautomaticallyprivate. privateallowscachesthatarespecictooneuser(e.g.,inabrowser)tostore theresponse;sharedcaches(e.g.,inaproxy)maynot. no-cacheforcescachestosubmittherequesttotheoriginserverforvalidation beforereleasingacachedcopy,everytime.Thisisusefultoassurethat authenticationisrespected(incombinationwithpublic),ortomaintainrigid freshness,withoutsacricingallofthebenetsofcaching. no-storeinstructscachesnottokeepacopyoftherepresentationunderany conditions. must-revalidatetellscachesthattheymustobeyanyfreshnessinformation yougivethemaboutarepresentation.HTTPallowscachestoservestale representationsunderspecialconditions;byspecifyingthisheader,youretelling thecachethatyouwantittostrictlyfollowyourrules. proxy-revalidatesimilartomust-revalidate,exceptthatitonlyapplies toproxycaches. Forexample:
Cache-Control: max-age=3600, must-revalidate
WhenbothCache-ControlandExpiresarepresent,Cache-Controltakes precedence.IfyouplantousetheCache-Controlheaders,youshouldhavealook
5 of 14
12/4/2012 1:24 AM
http://www.mnot.net/cache_docs/#WORK
attheexcellentdocumentationinHTTP1.1;seeReferencesandFurtherInformation.
Besidesusingfreshnessinformationandvalidation,thereareanumberofotherthings youcandotomakeyoursitemorecachefriendly. UseURLsconsistentlythisisthegoldenruleofcaching.Ifyouservethesame contentondierentpages,todierentusers,orfromdierentsites,itshoulduse thesameURL.Thisistheeasiestandmosteectivewaytomakeyoursitecache friendly.Forexample,ifyouuse/index.htmlinyourHTMLasareferenceonce, alwaysuseitthatway. Useacommonlibraryofimagesandotherelementsandreferbacktothemfrom dierentplaces. MakecachesstoreimagesandpagesthatdontchangeoftenbyusingaCacheControl: max-ageheaderwithalargevalue. Makecachesrecogniseregularlyupdatedpagesbyspecifyinganappropriate maxageorexpirationtime. Ifaresource(especiallyadownloadablele)changes,changeitsname.Thatway, youcanmakeitexpirefarinthefuture,andstillguaranteethatthecorrectversion isserved;thepagethatlinkstoitistheonlyonethatwillneedashortexpirytime. Dontchangelesunnecessarily.Ifyoudo,everythingwillhaveafalselyyoung Last-Modifieddate.Forinstance,whenupdatingyoursite,dontcopyoverthe entiresite;justmovethelesthatyouvechanged. Usecookiesonlywherenecessarycookiesarediculttocache,andarent neededinmostsituations.Ifyoumustuseacookie,limititsusetodynamicpages. MinimizeuseofSSLbecauseencryptedpagesarenotstoredbysharedcaches, usethemonlywhenyouhaveto,anduseimagesonSSLpagessparingly. CheckyourpageswithREDbotitcanhelpyouapplymanyoftheconceptsin thistutorial.
6 of 14
12/4/2012 1:24 AM
http://www.mnot.net/cache_docs/#WORK
Bydefault,mostscriptswontreturnavalidator(aLast-Modified orETag response header)orfreshnessinformation(ExpiresorCache-Control).Whilesomescripts reallyaredynamic(meaningthattheyreturnadierentresponseforeveryrequest), many(likesearchenginesanddatabasedrivensites)canbenetfrombeingcache friendly. Generallyspeaking,ifascriptproducesoutputthatisreproduciblewiththesame requestatalatertime(whetheritbeminutesordayslater),itshouldbecacheable.If thecontentofthescriptchangesonlydependingonwhatsintheURL,itis cacheable;iftheoutputdependsonacookie,authenticationinformationorother externalcriteria,itprobablyisnt. Thebestwaytomakeascriptcachefriendly(aswellasperformbetter)istodump itscontenttoaplainlewheneveritchanges.TheWebservercanthentreatitlike anyotherWebpage,generatingandusingvalidators,whichmakesyourlifeeasier. Remembertoonlywritelesthathavechanged,sotheLast-Modifiedtimesare preserved. Anotherwaytomakeascriptcacheableinalimitedfashionistosetanagerelated headerforasfarinthefutureaspractical.Althoughthiscanbedonewith Expires,itsprobablyeasiesttodosowithCache-Control: max-age,which willmaketherequestfreshforanamountoftimeaftertherequest. Ifyoucantdothat,youllneedtomakethescriptgenerateavalidator,andthen respondtoIf-Modified-Sinceand/orIf-None-Matchrequests.Thiscanbe donebyparsingtheHTTPheaders,andthenrespondingwith304 Not Modifiedwhenappropriate.Unfortunately,thisisnotatrivaltask. Someothertips; DontusePOSTunlessitsappropriate.ResponsestothePOSTmethodarent keptbymostcaches;ifyousendinformationinthepathorquery(viaGET), cachescanstorethatinformationforthefuture. DontembeduserspecicinformationintheURLunlessthecontentgeneratedis completelyuniquetothatuser. Dontcountonallrequestsfromausercomingfromthesamehost,because cachesoftenworktogether. GenerateContent-Lengthresponseheaders.Itseasytodo,anditwillallowthe responseofyourscripttobeusedinapersistentconnection.Thisallowsclientsto requestmultiplerepresentationsononeTCP/IPconnection,insteadofsettingupa connectionforeveryrequest.Itmakesyoursiteseemmuchfaster. SeetheImplementationNotesformorespecicinformation.
I UNDERSTAND THAT CACHING IS GOOD, BUT I NEED TO KEEP STATISTICS ON HOW MANY PEOPLE VISIT MY PAGE!
Ifyoumustknoweverytimeapageisaccessed,selectONEsmallitemonapage(or thepageitself),andmakeituncacheable,bygivingitasuitableheaders.Forexample, youcouldrefertoa1x1transparentuncacheableimagefromeachpage.The Refererheaderwillcontaininformationaboutwhatpagecalledit.
7 of 14
12/4/2012 1:24 AM
http://www.mnot.net/cache_docs/#WORK
8 of 14
12/4/2012 1:24 AM
http://www.mnot.net/cache_docs/#WORK
IM LOOKING FOR AN INTEGRATED WEB PUBLISHING SOLUTION. WHICH ONES ARE CACHE-AWARE?
Itvaries.Generallyspeaking,themorecomplexasolutionis,themoredicultitisto cache.Theworstareoneswhichdynamicallygenerateallcontentanddontprovide validators;theymaynotbecacheableatall.Speakwithyourvendorstechnicalsta formoreinformation,andseetheImplementationnotesbelow.
MY IMAGES EXPIRE A MONTH FROM NOW, BUT I NEED TO CHANGE THEM IN THE CACHES NOW!
TheExpiresheadercantbecircumvented;unlessthecache(eitherbrowserorproxy) runsoutofroomandhastodeletetherepresentations,thecachedcopywillbeused untilthen. Themosteectivesolutionistochangeanylinkstothem;thatway,completelynew representationswillbeloadedfreshfromtheoriginserver.Rememberthatanypage thatreferstotheserepresentationswillbecachedaswell.Becauseofthis,itsbestto makestaticimagesandsimilarrepresentationsverycacheable,whilekeepingthe HTMLpagesthatrefertothemonatightleash. Ifyouwanttoreloadarepresentationfromaspeciccache,youcaneitherforcea reload(inFirefox,holdingdownshiftwhilepressingreloadwilldothisbyissuinga Pragma: no-cacherequestheader)whileusingthecache.Or,youcanhavethe cacheadministratordeletetherepresentationthroughtheirinterface.
I RUN A WEB HOSTING SERVICE. HOW CAN I LET MY USERS PUBLISH CACHE-FRIENDLY PAGES?
IfyoureusingApache,considerallowingthemtouse.htaccesslesandproviding appropriatedocumentation. Otherwise,youcanestablishpredeterminedareasforvariouscachingattributesin eachvirtualserver.Forinstance,youcouldspecifyadirectory/cache1mthatwillbe cachedforonemonthafteraccess,anda/nocacheareathatwillbeservedwith headersinstructingcachesnottostorerepresentationsfromit. Whateveryouareabletodo,itisbesttoworkwithyourlargestcustomersrston caching.Mostofthesavings(inbandwidthandinloadonyourservers)willbe realizedfromhighvolumesites.
IVE MARKED MY PAGES AS CACHEABLE, BUT MY BROWSER KEEPS REQUESTING THEM ON EVERY REQUEST. HOW DO I FORCE THE CACHE TO KEEP REPRESENTATIONS OF THEM?
Cachesarentrequiredtokeeparepresentationandreuseit;theyreonlyrequiredto notkeeporusethemundersomeconditions.Allcachesmakedecisionsaboutwhich representationstokeepbasedupontheirsize,type(e.g.,imagevs.html),orbyhow muchspacetheyhavelefttokeeplocalcopies.Yoursmaynotbeconsideredworth keepingaround,comparedtomorepopularorlargerrepresentations. Somecachesdoallowtheiradministratorstoprioritizewhatkindsofrepresentations arekept,andsomeallowrepresentationstobepinnedincache,sothattheyre alwaysavailable.
9 of 14
12/4/2012 1:24 AM
http://www.mnot.net/cache_docs/#WORK
distribution,theyarenotturnedonbydefault.Tondoutifthemodulesareenabled inyourserver,ndthehttpdbinaryandrunhttpd -l;thisshouldprintalistofthe availablemodules(notethatthisonlylistscompiledinmodules;onlaterversionsof Apache,usehttpd -Mtoincludedynamicallyloadedmodulesaswell).Themodules werelookingforaremod_expiresandmod_headers. Iftheyarentavailable,andyouhaveadministrativeaccess,youcanrecompile Apachetoincludethem.Thiscanbedoneeitherbyuncommentingthe appropriatelinesintheCongurationle,orusingthe-enablemodule=expiresand-enable-module=headersargumentstocongure(1.3 orgreater).ConsulttheINSTALLlefoundwiththeApachedistribution. OnceyouhaveanApachewiththeappropriatemodules,youcanusemod_expiresto specifywhenrepresentationsshouldexpire,eitherin.htaccesslesorintheservers access.confle.Youcanspecifyexpiryfromeitheraccessormodicationtime,and applyittoaletypeorasadefault.Seethemoduledocumentationformore information,andspeakwithyourlocalApacheguruifyouhavetrouble. ToapplyCache-Controlheaders,youllneedtousethemod_headersmodule, whichallowsyoutospecifyarbitraryHTTPheadersforaresource.Seethe mod_headersdocumentation. Heresanexample.htaccesslethatdemonstratestheuseofsomeheaders. .htaccesslesallowwebpublisherstousecommandsnormallyonlyfoundin congurationles.Theyaectthecontentofthedirectorytheyreinandtheir subdirectories.Talktoyourserveradministratortondoutiftheyreenabled.
### activate mod_expires ExpiresActive On ### Expire .gif's 1 month from when they're accessed ExpiresByType image/gif A2592000 ### Expire everything else 1 day from when it's last modified ### (this uses the Alternative syntax) ExpiresDefault "modification plus 1 day" ### Apply a Cache-Control header to index.html <Files index.html> Header append Cache-Control "public, must-revalidate" </Files>
MICROSOFT IIS
MicrosoftsInternetInformationServermakesitveryeasytosetheadersina somewhatexibleway.Notethatthisisonlypossibleinversion4oftheserver,which willrunonlyonNTServer. Tospecifyheadersforanareaofasite,selectitintheAdministration Tools interface,andbringupitsproperties.AfterselectingtheHTTP Headerstab,you shouldseetwointerestingareas;Enable Content ExpirationandCustom HTTP headers.Therstshouldbeselfexplanatory,andthesecondcanbeusedto applyCacheControlheaders. SeetheASPsectionbelowforinformationaboutsettingheadersinActiveServer Pages.ItisalsopossibletosetheadersfromISAPImodules;refertoMSDNfor details.
10 of 14
12/4/2012 1:24 AM
http://www.mnot.net/cache_docs/#WORK
Becausetheemphasisinserversidescriptingison dynamiccontent,itdoesntmakeforvery cacheablepages,evenwhenthecontentcouldbe cached.Ifyourcontentchangesoften,butnoton everypagehit,considersettingaCacheControl: maxageheader;mostusersaccesspagesagainin arelativelyshortperiodoftime.Forinstance, whenusershitthebackbutton,ifthereisntany validatororfreshnessinformationavailable,theyll havetowaituntilthepageisredownloadedfrom theservertoseeit.
CGI
CGIscriptsareoneofthemostpopularwaystogeneratecontent.Youcaneasily appendHTTPresponseheadersbyaddingthembeforeyousendthebody;MostCGI implementationsalreadyrequireyoutodothisfortheContent-Typeheader.For instance,inPerl;
#!/usr/bin/perl print "Content-type: text/html\n"; print "Expires: Thu, 29 Oct 1998 17:04:19 GMT\n"; print "\n"; ### the content body follows...
Thiswillmakethescriptcacheablefor10minutesaftertherequest,sothatiftheuser hitsthebackbutton,theywontberesubmittingtherequest. TheCGIspecicationalsomakesrequestheadersthattheclientsendsavailableinthe environmentofthescript;eachheaderhasHTTP_prependedtoitsname.So,ifa clientmakesanIf-Modified-Sincerequest,itwillshowupas HTTP_IF_MODIFIED_SINCE. Seealsothecgi_buerlibrary,whichautomaticallyhandlesETaggenerationand validation,Content-LengthgenerationandgzipcontentcodingforPerlandPython CGIscriptswithaonelineinclude.ThePythonversioncanalsobeusedtowrap arbitraryCGIscriptswith.
11 of 14
12/4/2012 1:24 AM
http://www.mnot.net/cache_docs/#WORK
PHP
PHPisaserversidescriptinglanguagethat,whenbuiltintotheserver,canbeusedto embedscriptsinsideapagesHTML,muchlikeSSI,butwithafarlargernumberof options.PHPcanbeusedasaCGIscriptonanyWebserver(UnixorWindows),oras anApachemodule. Bydefault,representationsprocessedbyPHParenotassignedvalidators,andare thereforeuncacheable.However,developerscansetHTTPheadersbyusingthe Header()function. Forexample,thiswillcreateaCacheControlheader,aswellasanExpiresheader threedaysinthefuture:
<?php Header("Cache-Control: must-revalidate"); $offset = 60 * 60 * 24 * 3; $ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT"; Header($ExpStr); ?>
RememberthattheHeader()functionMUSTcomebeforeanyotheroutput. Asyoucansee,youllhavetocreatetheHTTPdateforanExpiresheaderbyhand; PHPdoesntprovideafunctiontodoitforyou(althoughrecentversionshavemade iteasier;seethePHPsdatedocumentation).Ofcourse,itseasytosetaCacheControl: max-age header,whichisjustasgoodformostsituations. Formoreinformation,seethemanualentryforheader. Seealsothecgi_buerlibrary,whichautomaticallyhandlesETaggenerationand validation,Content-LengthgenerationandgzipcontentcodingforPHPscripts withaonelineinclude.
COLD FUSION
ColdFusion,byMacromediaisacommercialserversidescriptingengine,with supportforseveralWebserversonWindows,LinuxandseveralavorsofUnix. ColdFusionmakessettingarbitraryHTTPheadersrelativelyeasy,withtheCFHEADER tag.Unfortunately,theirexampleforsettinganExpiresheader,asbelow,isabit misleading.
<CFHEADER NAME="Expires" VALUE="#Now()#">
12 of 14
12/4/2012 1:24 AM
http://www.mnot.net/cache_docs/#WORK
WhensettingHTTP headersfromASPs, makesureyoueither placetheResponse methodcallsbefore anyHTML generation,oruse Response.Buffer tobuertheoutput. Also,notethatsome versionsofIISseta Cache-Control: privateheaderon mustbedeclared publictobecacheable bysharedcaches.
WEB-CACHING.COM
Anexcellentintroductiontocachingconcepts,withlinkstootheronlineresources.
REDBOT
ExaminesHTTPresourcestodeterminehowtheywillinteractwithWebcaches,and generallyhowwelltheyusetheprotocol.
CGI_BUFFER LIBRARY
OnelineincludeinPerlCGI,PythonCGIandPHPscriptsautomaticallyhandles ETaggenerationandvalidation,ContentLengthgenerationandgzipContent Encodingcorrectly.ThePythonversioncanalsobeusedasawrapperaround arbitraryCGIscripts.
13 of 14
12/4/2012 1:24 AM
http://www.mnot.net/cache_docs/#WORK
14 of 14
12/4/2012 1:24 AM