Tải bản đầy đủ

OReilly apache the definitive guide 3rd edition dec 2002 ISBN 0596002033


Tableof

Contents
• Index
• Reviews
• Examples
Reader

Reviews
• Errata



















ApacheTheDefinitiveGuide,3rdEdition
ByBenLaurie,PeterLaurie


Publisher :O'Reilly
PubDate :December2002
ISBN :0-596-00203-3
UpdatedtocoverthechangesinApache'slatestrelease,
2.0,aswellasApache1.3,thisusefulguidediscusseshow
toobtain,setup,secure,modify,andtroubleshootthe
ApachesoftwareonbothUnixandWindowssystems.In
additiontocoveringtheinstallationandconfigurationof
mod_perlandTomcat,thebookexaminesPHP,Cocoon,
andothernewtechnologiesthatareassociatedwiththe
Apachewebserver.

777







Copyright
Preface
WhoWroteApache,andWhy?
TheDemonstrationCode
ConventionsUsedinThisBook
OrganizationofThisBook
Acknowledgments










Chapter1.GettingStarted
Section1.1.WhatDoesaWebServerDo?
Section1.2.HowApacheWorks
Section1.3.ApacheandNetworking
Section1.4.HowHTTPClientsWork
Section1.5.WhatHappensattheServerEnd?
Section1.6.PlanningtheApacheInstallation
Section1.7.Windows?











































Section1.8.WhichApache?
Section1.9.InstallingApache
Section1.10.BuildingApache1.3.XUnderUnix
Section1.11.NewFeaturesinApachev2
Section1.12.MakingandInstallingApachev2UnderUnix
Section1.13.ApacheUnderWindows








Chapter2.ConfiguringApache:TheFirstSteps
Section2.1.What'sBehindanApacheWebSite?
Section2.2.site.toddle
Section2.3.SettingUpaUnixServer
Section2.4.SettingUpaWin32Server
Section2.5.Directives
Section2.6.SharedObjects











Chapter3.TowardaRealWebSite
Section3.1.MoreandBetterWebSites:site.simple
Section3.2.Butterthlies,Inc.,GetsGoing
Section3.3.BlockDirectives
Section3.4.OtherDirectives
Section3.5.HTTPResponseHeaders
Section3.6.Restarts
Section3.7..htaccess
Section3.8.CERNMetafiles
Section3.9.Expirations






Chapter4.VirtualHosts
Section4.1.TwoSitesandApache
Section4.2.VirtualHosts
Section4.3.TwoCopiesofApache
Section4.4.DynamicallyConfiguredVirtualHosting
Chapter5.Authentication





















































Section5.1.AuthenticationProtocol
Section5.2.AuthenticationDirectives
Section5.3.PasswordsUnderUnix
Section5.4.PasswordsUnderWin32
Section5.5.PasswordsovertheWeb
Section5.6.FromtheClient'sPointofView
Section5.7.CGIScripts
Section5.8.VariationsonaTheme
Section5.9.Order,Allow,andDeny
Section5.10.DBMFilesonUnix
Section5.11.DigestAuthentication
Section5.12.AnonymousAccess
Section5.13.Experiments
Section5.14.AutomaticUserInformation
Section5.15.Using.htaccessFiles
Section5.16.Overrides








Chapter6.ContentDescriptionandModification
Section6.1.MIMETypes
Section6.2.ContentNegotiation
Section6.3.LanguageNegotiation
Section6.4.TypeMaps
Section6.5.BrowsersandHTTP1.1
Section6.6.Filters






Chapter7.Indexing
Section7.1.MakingBetterIndexesinApache
Section7.2.MakingOurOwnIndexes
Section7.3.Imagemaps
Section7.4.ImageMapDirectives

Chapter8.Redirection

Section8.1.Alias







































Section8.2.Rewrite
Section8.3.Speling







Chapter9.Proxying
Section9.1.Security
Section9.2.ProxyDirectives
Section9.3.ApparentBug
Section9.4.Performance
Section9.5.Setup






Chapter10.Logging
Section10.1.LoggingbyScriptandDatabase
Section10.2.Apache'sLoggingFacilities
Section10.3.ConfigurationLogging
Section10.4.Status













Chapter11.Security
Section11.1.InternalandExternalUsers
Section11.2.BinarySignatures,VirtualCash
Section11.3.Certificates
Section11.4.Firewalls
Section11.5.LegalIssues
Section11.6.SecureSocketsLayer(SSL)
Section11.7.Apache'sSecurityPrecautions
Section11.8.SSLDirectives
Section11.9.CipherSuites
Section11.10.SecurityinRealLife
Section11.11.FutureDirections

Chapter12.RunningaBigWebSite

Section12.1.MachineSetup

Section12.2.ServerSecurity

Section12.3.ManagingaBigSite








































Section12.4.SupportingSoftware
Section12.5.Scalability
Section12.6.LoadBalancing

Chapter13.BuildingApplications

Section13.1.WebSitesasApplications

Section13.2.ProvidingApplicationLogic

Section13.3.XML,XSLT,andWebApplications








Chapter14.Server-SideIncludes
Section14.1.FileSize
Section14.2.FileModificationTime
Section14.3.Includes
Section14.4.ExecuteCGI
Section14.5.Echo
Section14.6.Apachev2:SSIFilters

Chapter15.PHP

Section15.1.InstallingPHP

Section15.2.Site.php











Chapter16.CGIandPerl
Section16.1.TheWorldofCGI
Section16.2.TellingApacheAbouttheScript
Section16.3.SettingEnvironmentVariables
Section16.4.Cookies
Section16.5.ScriptDirectives
Section16.6.suEXEConUnix
Section16.7.Handlers
Section16.8.Actions
Section16.9.Browsers
Chapter17.mod_perl














































Section17.1.Howmod_perlWorks
Section17.2.mod_perlDocumentation
Section17.3.Installingmod_perl—TheSimpleWay
Section17.4.ModifyingYourScriptstoRunUndermod_perl
Section17.5.GlobalVariables
Section17.6.StrictPregame
Section17.7.LoadingChanges
Section17.8.OpeningandClosingFiles
Section17.9.ConfiguringApachetoUsemod_perl

Chapter18.mod_jservandTomcat

Section18.1.mod_jserv

Section18.2.Tomcat

Section18.3.ConnectingTomcattoApache








Chapter19.XMLandCocoon
Section19.1.XML
Section19.2.XMLandPerl
Section19.3.Cocoon
Section19.4.Cocoon1.8andJServ
Section19.5.Cocoon2.0.3andTomcat
Section19.6.TestingCocoon











Chapter20.TheApacheAPI
Section20.1.Documentation
Section20.2.APR
Section20.3.Pools
Section20.4.Per-ServerConfiguration
Section20.5.Per-DirectoryConfiguration
Section20.6.Per-RequestInformation
Section20.7.AccesstoConfigurationandRequestInformation
Section20.8.Hooks,OptionalHooks,andOptionalFunctions
Section20.9.Filters,Buckets,andBucketBrigades

























Section20.10.Modules








Chapter21.WritingApacheModules
Section21.1.Overview
Section21.2.StatusCodes
Section21.3.TheModuleStructure
Section21.4.ACompleteExample
Section21.5.GeneralHints
Section21.6.PortingtoApache2.0








AppendixA.TheApache1.xAPI
SectionA.1.Pools
SectionA.2.Per-ServerConfiguration
SectionA.3.Per-DirectoryConfiguration
SectionA.4.Per-RequestInformation
SectionA.5.AccesstoConfigurationandRequestInformation
SectionA.6.Functions
Colophon
Index

Copyright
Copyright©O'Reilly&Associates,Inc.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'Reilly&Associates,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reilly&Associatesbooksmaybepurchasedforeducational,
business,orsalespromotionaluse.Onlineeditionsarealsoavailable
formosttitles(http://safari.oreilly.com).Formoreinformation,


contactourcorporate/institutionalsalesdepartment:(800)998-9938
orcorporate@oreilly.com.
NutshellHandbook,theNutshellHandbooklogo,andtheO'Reilly
logoareregisteredtrademarksofO'Reilly&Associates,Inc.Manyof
thedesignationsusedbymanufacturersandsellerstodistinguishtheir
productsareclaimedastrademarks.Wherethosedesignationsappear
inthisbook,andO'Reilly&Associates,Inc.wasawareofa
trademarkclaim,thedesignationshavebeenprintedincapsorinitial
caps.TheassociationbetweentheimageofAppaloosahorseandthe
topicofApacheisatrademarkofO'Reilly&Associates,Inc.
Whileeveryprecautionhasbeentakeninthepreparationofthisbook,
thepublisherandauthorsassumenoresponsibilityforerrorsor
omissions,orfordamagesresultingfromtheuseoftheinformation
containedherein.


Preface
Apache:TheDefinitiveGuide,ThirdEdition,isprincipallyaboutthe
Apacheweb-serversoftware.Weexplainwhatawebserverisand
howitworks,butourassumptionisthatmostofourreadershaveused
theWorldWideWebandunderstandinpracticaltermshowitworks,
andthattheyarenowthinkingaboutrunningtheirownserversand
sites.
Thisbooktakesthereaderthroughtheprocessofacquiring,
compiling,installing,configuring,andmodifyingApache.We
exercisemostofthepackage'sfunctionsbyshowingasetofexample
sitesthattakeareasonablytypicalwebbusiness—inourcase,a
postcardpublisher—throughaprocessofdevelopmentand
increasingcomplexity.However,wehavedeliberatelytriedtomake
eachsiteassimpleaspossible,focusingontheparticularfeature
beingdescribed.Eachsiteisprettywellself-contained,sothatthe
readercanrefertoitwhilefollowingthetextwithouthavingto
disentanglethemeatfromextraneousvegetables.Ifdesired,itis
possibletoinstallandruneachsiteonasuitablesystem.
Perhapsitisworthsayingwhatthisbookisnot.Itisnotamanual,in
thesenseofformallydocumentingeverycommand—suchamanual
existsontheApachesiteandhasbeenmuchimprovedwithVersions
1.3and2.0;weassumethatifyouwanttouseApache,youwill
downloaditandkeepitathand.Rather,ifthemanualisaroadmap
thattellsyouhowtogetsomewhere,thisbooktriestobeatourist
guidethattellsyouwhyyoumightwanttomakethejourney.
Inpassing,wedoreproducesomesectionsofthewebsitemanual
simplytosavethereaderthetroubleoflookinguptheformal
definitionsasshefollowstheargument.Occasionally,wefoundthe


manualtexthardtofollowandinthosecaseswehavechangedthe
wordingslightly.Wehavealsointerspersedcommentsasseemed
usefulatthetime.
ThisisnotabookaboutHTMLorcreatingwebpages,oroneabout
websecurityorevenaboutrunningawebsite.Theseareallcomplex
subjectsthatshouldbeeithertreatedthoroughlyorleftalone.Asa
result,awebmaster'slibrarymightincludebooksonthefollowing
topics:
TheWebandhowitworks
HTML—formaldefinitions,whatyoucandowithit
Howtodecidewhatsortofwebsiteyouwant,howtoorganizeit,
andhowtoprotectit
Howtoimplementthesiteyouwantusingoneoftheavailable
servers(forinstance,Apache)
HandbooksonJava,Perl,andotherlanguages
Security
Apache:TheDefinitiveGuideisjustoneofthesixorsopossible
titlesinthefourthcategory.
Apacheisaversatilepackageandisbecomingmoreversatileevery
day,sowehavenottriedtoillustrateeverypossiblecombinationof
commands;thatwouldrequireabookofamillionpagesorso.Rather,
wehavetriedtosuggestlinesofdevelopmentthatatypical
webmastercouldfollowonceanunderstandingofthebasicconcepts
isachieved.
Werealizedfromourownexperiencethatthehardeststageof


learninghowtouseApacheinareal-lifecontextisrightatthe
beginning,wherethenovicewebmasteroftenhastogetApache,a
scriptinglanguage,andadatabasemanagertocollaborate.Thiscanbe
verypuzzling.Inthisneweditionwehavethereforeincludedagood
dealofnewmaterialwhichtriestotakethereaderuptheseconceptual
precipices.Oncethecollaborationisworking,developmentismuch
easier.Thesenewchaptersarenotintendedtobeanexperts'account
of,say,theinteractionbetweenApache,Perl,andMySQL—buta
simplebeginners'guide,explaininghowtomakethesethingswork
withApache.Intheprocesswemakesomecomments,fromourown
experience,onthemeritsofthevarioussoftwareproductsfromwhich
theuserhastochoose.
Aswiththefirstandsecondeditions,writingthebookwassomething
ofaracewithApache'sdevelopers.Wewantedtobereadyassoonas
Version2wasstable,butnotbeforethedevelopershadfinished
addingnewfeatures.
Inmanyoftheexamplesthatfollow,themotivationforwhatwemake
Apachedoissimpleenoughandrequireslittleexplanation(for
example,thedifferentindexformatsinChapter7).Elsewhere,wefeel
thatthewebmasterneedstobeawareofwiderissues(forinstance,the
securityissuesdiscussedinChapter11)beforemakingsensible
decisionsabouthissite'sconfiguration,andwehavenothesitatedto
branchouttodealwiththem.

WhoWroteApache,andWhy?
Apachegetsitsnamefromthefactthatitconsistsofsomeexisting
codeplussomepatches.TheFAQFAQisnetspeakforFrequently
AskedQuestions.Mostsites/subjectshaveanFAQfilethattellsyou
whatthethingis,whyitis,andwhereit'sgoing.Itisperfectly
reasonableforthenewcomertoaskfortheFAQtolookupanything


newtoher,andindeedthisisasensiblethingtodo,sinceitreduces
thenumberofquestionsasked.Apache'sFAQcanbefoundat
http://www.apache.org/docs/FAQ.html.thinksthatthisiscute;others
maythinkit'sthesortofjokethatgetsprogrammersabadname.A
moreresponsiblegroupthinksthatApacheisanappropriatetitle
becauseoftheresourcefulnessandadaptabilityoftheAmerican
Indiantribe.
YouhavetounderstandthatApacheisfreetoitsusersandiswritten
byateamofvolunteerswhodonotgetpaidfortheirwork.Whether
theydecidetoincorporateyouroranyoneelse'sideasisentirelyupto
them.Ifyoudon'tlikewhattheydo,feelfreetocollectateamand
writeyourownwebserverortoadapttheexistingApachecode—as
manyhave.
ThefirstwebserverwasbuiltbytheBritishphysicistTimBernersLeeatCERN,theEuropeanCentreforNuclearResearchatGeneva,
Switzerland.TheimmediateancestorofApachewasbuiltbytheU.S.
government'sNCSA,theNationalCenterforSupercomputing
Applications.Becausethiscodewaswrittenwith(American)
taxpayers'money,itisavailabletoall;youcan,ifyoulike,download
thesourcecodeinCfromhttp://www.ncsa.uiuc.edu,payingdue
attentiontothelicenseconditions.
Therewerethosewhothoughtthatthingscouldbedonebetter,andin
theFAQforApache(athttp://www.apache.org),weread:
...Apachewasoriginallybasedoncodeandideasfoundinthe
mostpopularHTTPserverofthetime,NCSAhttpd1.3(early
1995).
Thatphrase"ofthetime"isnice.Itusuallyreferstogoodtimesback
inthe1700sortheearlydaysoftechnologyinthe1900s.Buthereit
meansbackinthedeliquescentbogsofafewyearsago!


WhiletheApachesiteisopentoall,Apacheiswrittenbyaninvited
groupof(wehope)reasonablygoodprogrammers.Oneoftheauthors
ofthisbook,Ben,isamemberofthisgroup.
Whydotheybother?Whydotheseprogrammers,whopresumably
couldbewellpaidfordoingsomethingelse,situpnightstoworkon
Apacheforourbenefit?Thereisnosuchthingasafreelunch,sothey
doitforanumberoftypicallyhumanreasons.Onemightlist,inno
particularorder:
Theywanttodosomethingmoreinterestingthantheirdayjob,
whichmightbewritingstockcontrolpackagesforBigBins,Inc.
Theywanttobeinvolvedontheedgeofwhatishappening.
Workingonaprojectlikethisisaprettygoodwaytokeepup-todate.Afterthatcomesconsultancyonthenexthotproject.
Themoreworldlyonesmightrememberhow,backintheold
daysof1995,quitealotofthepeopleworkingonthewebserver
atNCSAleftforathingcalledNetscapeandbecame,inthe
passageoftheage,zillionaires.
It'sfun.Developinggoodsoftwareisinterestingandamusing,
andyougettomeetandworkwithothercleverpeople.
Theyarenotdoingthebitthatprogrammershate:explainingto
enduserswhytheirtreasureisn'tworkingandtryingtofixitin10
minutesflat.IfyouwantsupportonApache,youhavetoconsult
oneofseveralcommercialorganizations(seeAppendixA),who,
quiteproperly,wanttobepaidfordoingtheworkeveryone
loathes.

TheDemonstrationCode


Thecodeforthedemonstrationwebsitesreferredtothroughoutthe
bookisavailableathttp://www.oreilly.com/catalog/apache3/.It
containstherequisiteREADMEfilewithinstallationinstructionsand
otherusefulinformation.Thecontentsofthedownloadareorganized
intotwodirectories:
install/
Thisdirectorycontainsscriptstoinstallthesamplesites:
install
Runthisscripttoinstallthesites.
install.conf
Unixconfigurationfileforinstall.
installwin.conf
Win32configurationfileforinstall.
sites/
Thisdirectorycontainsthesamplesitesusedinthebook.

ConventionsUsedinThisBook
Thissectioncoversthevariousconventionsusedinthisbook.
TypographicConventions
Constantwidth


UsedforHTTPheaders,statuscodes,MIMEcontenttypes,
directivesinconfigurationfiles,commands,options/switches,
functions,methods,variablenames,andcodewithinbodytext
Constantwidthbold

Usedincodesegmentstoindicateinputtobetypedinbytheuser
Constantwidthitalic

Usedforreplaceableitemsincodeandtext
Italic
Usedforfilenames,pathnames,newsgroupnames,Internet
addresses(URLs),emailaddresses,variablenames(exceptin
examples),termsbeingintroduced,programnames,subroutine
names,CGIscriptnames,hostnames,usernames,andgroup
names
Icons

TextmarkedwiththisiconappliestotheUnixversionofApache.

TextmarkedwiththisiconappliestotheWin32versionofApache.
Thisicondesignatesanoterelatingtothesurroundingtext.




Thisicondesignatesawarningrelatedtothesurroundingtext.

Pathnames
Weusethetextconvention.../toindicateyourpathtothe
demonstrationsites,whichmaywellbedifferentfromours.For
instance,onourApachemachine,wekeptallthedemonstrationsites
inthedirectory/usr/www.So,forexample,ourpathwouldbe
/usr/www/site.simple.Youmightwanttokeepthesitessomewhere
otherthan/usr/www,sowerefertothepathas.../site.simple.
Don'ttype.../intoyourcomputer.Theattemptwillupsetit!
Directives
Apacheiscontrolledthroughroughly150directives.Foreach
directive,aformalexplanationisgiveninthefollowingformat:
Directive



Syntax
Whereused



Anexplanationofthedirectiveislocatedhere.
So,forinstance,wehavethefollowingdirective:
ServerAdmin



ServerAdminemailaddress
Serverconfig,virtualhost




ServerAdmingivestheemailaddressforcorrespondence.It

automaticallygenerateserrormessagessotheuserhassomeoneto
writetoincaseofproblems.
TheWhereusedlineexplainstheappropriateenvironmentforthe
directive.Thiswillbecomeclearerlater.

OrganizationofThisBook
Thechaptersthatfollowandtheircontentsarelistedhere:
Chapter1
Coverswebservers,howApacheworks,TCP/IP,HTTP,
hostnames,whataclientdoes,whathappensattheserverend,
choosingaUnixversion,andcompilingandinstallingApache
underbothUnixandWin32.
Chapter2
DiscussesgettingApachetorun,creatingApacheusers,runtime
flags,permissions,andsite.simple.
Chapter3
Introducesademonstrationbusiness,Butterthlies,Inc.;some
HTML;defaultindexingofwebpages;serverhousekeeping;and
blockdirectives.
Chapter4
Explainshowtoconnectwebsitestonetworkaddresses,
includingthecommoncasewheremorethanonewebsiteis
hostedatagivennetworkaddress.


Chapter5
Explainscontrollingaccess,collectinginformationaboutclients,
cookies,DBMcontrol,digestauthentication,andanonymous
access.
Chapter6
Coverscontentandlanguagearbitration,typemaps,and
expirationofinformation.
Chapter7
Discussesbetterindexes,indexoptions,yourownindexes,and
imagemaps.
Chapter8
DescribesAlias,ScriptAlias,andtheamazingRewritemodule.
Chapter9
Coversremoteproxiesandproxycaching.
Chapter10
ExplainsApache'sfacilitiesfortrackingactivityonyourweb
sites.
Chapter11
ExploresthemanyaspectsofprotectinganApacheserverandits
contentfromuninvitedguestsandintruders,includinguser
validation,binarysignatures,virtualcash,certificates,firewalls,
packetfiltering,securesocketslayer(SSL),legalissues,patent


rights,nationalsecurity,andApache-SSLdirectives.
Chapter12
Explainsbestpracticesforrunninglargesites,includingsupport
formultiplecontent-creators,separatingtestsitesfromproduction
sites,andintegratingthesitewithotherInternettechnologies.
Chapter13
ExplorestheoptionsavailableforusingApachetohost
automaticallychangingcontentandinteractiveapplications.
Chapter14
ExplainsusingruntimecommandsinyourHTMLandXSSI—a
moresecureserver-sideinclude.
Chapter15
ExplainshowtoinstallandconfigurePHP,withanexamplefor
connectingittoMySQL.
Chapter16
Demonstratesaliases,logs,HTMLforms,ashellscript,aCGI
scriptinPerl,environmentvariables,andusingMySQLthrough
PerlandApache.
Chapter17
Demonstrateshowtoinstall,configure,andusethemod_perl
moduleforefficientprocessingofPerlapplications.
Chapter18


ExplainshowtoinstallthesetwomodulesforsupportingJavain
theApacheenvironment.
Chapter19
ExplainshowtouseXMLinconjunctionwithApacheandhow
toinstallandconfiguretheCocoonsetoftoolsforpresenting
XMLcontent.
Chapter20
ExploresthefoundationsoftheApache2.0API.
Chapter21
DescribeshowtocreateApachemodulesusingtheApache2.0
ApachePortableRuntime,includinghowtoportmodulesfrom
1.3to2.0.
AppendixA
Describespools;per-server,per-directory,andper-request
information;functions;warnings;andparsing.
Inaddition,theApacheQuickReferenceCardprovidesanoutlineof
Apache1.3and2.0syntax.

Acknowledgments
First,thankstoRobertS.Thau,whogavetheworldtheApacheAPI
andthecodethatimplementsit,andtotheApacheGroup,who
workedonitbeforeandhaveworkedonitsince.ThankstoEric
YoungandTimHudsonforgivingSSLeaytotheWeb.


ThankstoBryanBlank,AramMirzadeh,ChuckMurcko,andRandy
Terbush,whoreadearlydraftsofthefirsteditiontextandmademany
usefulsuggestions;andtoJohnAckermann,GeoffMeek,andShane
Owenby,whodidthesameforthesecondedition.Forthethird
edition,wewouldliketothankourreviewersEvelynMitchell,Neil
Neely,Lemon,Dirk-WillemvanGulik,RichardSonnen,DavidReid,
JoeJohnston,MikeStok,andStevenChampeon.
WewouldalsoliketoofferspecialthankstoAndrewFordforgiving
uspermissiontoreprinthisApacheQuickReferenceCard.
ManythankstoSimonSt.Laurent,oureditoratO'Reilly,who
patientlyturnedourtextintoabook—again.Thetwolayersof
blundersthatremainareourowncontribution.
Andfinally,thankstoCamillavonMassenbachandBarbaraLaurie,
whohavecontinuedtoputupwithuswhilewerewrotethisbook.


CONTENTS


Chapter1.GettingStarted
1.1WhatDoesaWebServerDo?
1.2HowApacheWorks
1.3ApacheandNetworking
1.4HowHTTPClientsWork
1.5WhatHappensattheServerEnd?
1.6PlanningtheApacheInstallation
1.7Windows?
1.8WhichApache?
1.9InstallingApache
1.10BuildingApache1.3.XUnderUnix
1.11NewFeaturesinApachev2
1.12MakingandInstallingApachev2UnderUnix
1.13ApacheUnderWindows
ApacheisthedominantwebserverontheInternettoday,fillingakeyplacein
theinfrastructureoftheInternet.Thischapterwillexplorewhatwebserversdo
andwhyyoumightchoosetheApachewebserver,examinehowyourweb
serverfitsintotherestofyournetworkinfrastructure,andconcludebyshowing
youhowtoinstallApacheonavarietyofdifferentsystems.

1.1WhatDoesaWebServerDo?
ThewholebusinessofawebserveristotranslateaURLeitherintoafilename,
andthensendthatfilebackovertheInternet,orintoaprogramname,andthen
runthatprogramandsenditsoutputback.Thatisthemeatofwhatitdoes:all
therestistrimming.
WhenyoufireupyourbrowserandconnecttotheURLofsomeone'shomepage
—saythenotionalhttp://www.butterthlies.com/weshallmeetlateron—you
sendamessageacrosstheInternettothemachineatthataddress.Thatmachine,
youhope,isupandrunning;itsInternetconnectionisworking;anditisreadyto
receiveandactonyourmessage.


URLstandsforUniformResourceLocator.AURLsuchas
http://www.butterthlies.com/comesinthreeparts:

:///
So,inourexample,ishttp,meaningthatthebrowsershould
useHTTP(HypertextTransferProtocol);is
www.butterthlies.com;andis/,traditionallymeaning
thetoppageofthehost.[1]ThemaycontaineitheranIPaddressora
name,whichthebrowserwillthenconverttoanIPaddress.UsingHTTP1.1,
yourbrowsermightsendthefollowingrequesttothecomputeratthatIP
address:

GET/HTTP/1.1
Host:www.butterthlies.com
Therequestarrivesatport80(thedefaultHTTPport)onthehost
www.butterthlies.com.Themessageisagaininfourparts:amethod(anHTTP
method,notaURLmethod),thatinthiscaseisGET,butcouldequallybePUT,
POST,DELETE,orCONNECT;theUniformResourceIdentifier(URI)/;
theversionoftheprotocolweareusing;andaseriesofheadersthatmodifythe
request(inthiscase,aHostheader,whichisusedforname-basedvirtual
hosting:seeChapter4).Itisthenuptothewebserverrunningonthathostto
makesomethingofthismessage.
Thehostmachinemaybeawholeclusterofhypercomputerscostinganoil
sheik'sransomorjustahumblePC.Ineithercase,ithadbetterberunningaweb
server,aprogramthatlistenstothenetworkandacceptsandactsonthissortof
message.

1.1.1CriteriaforChoosingaWebServer
Whatdowewantawebservertodo?Itshould:
Runfast,soitcancopewithalotofrequestsusingaminimumof


hardware.
Supportmultitasking,soitcandealwithmorethanonerequestatonceand
sothatthepersonrunningitcanmaintainthedataithandsoutwithout
havingtoshuttheservicedown.Multitaskingishardtoarrangewithina
program:theonlywaytodoitproperlyistoruntheserverona
multitaskingoperatingsystem.
Authenticaterequesters:somemaybeentitledtomoreservicesthanothers.
Whenwecometohandlingmoney,thisfeature(seeChapter11)becomes
essential.
Respondtoerrorsinthemessagesitgetswithanswersthatmakesensein
thecontextofwhatisgoingon.Forinstance,ifaclientrequestsapagethat
theservercannotfind,theservershouldrespondwitha"404"error,which
isdefinedbytheHTTPspecificationtomean"pagedoesnotexist."
Negotiateastyleandlanguageofresponsewiththerequester.Forinstance,
itshould—ifthepeoplerunningtheservercanrisetothechallenge—be
abletorespondinthelanguageoftherequester'schoice.Thisability,of
course,canopenupyoursitetoalotmoreaction.Therearepartsofthe
worldwherearesponseinthewronglanguagecanbeabadthing.
Supportavarietyofdifferentformats.Onamoretechnicallevel,auser
mightwantJPEGimagefilesratherthanGIF,orTIFFratherthaneitherof
those.HemightwanttextinvdiformatratherthanPostScript.
Beabletorunasaproxyserver.Aproxyserveracceptsrequestsforclients,
forwardsthemtotherealservers,andthensendstherealservers'responses
backtotheclients.Therearetworeasonswhyyoumightwantaproxy
server:

Theproxymightberunningonthefarsideofafirewall(see
Chapter11),givingitsusersaccesstotheInternet.
Theproxymightcachepopularpagestosavereaccessing
them.


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×